Reputation: 21
I have been having a problem with this for hours now, and I don't know what is wrong. I am trying to make a list of registered users in Laravel but it keeps giving me the error:
"Undefined variable: users (View: C:\xampp\htdocs\laraveltest1\links\resources\views\home.blade.php)"
I have asked around on the Laravel Discord server. We've tried several things with no luck such as changing names and changing up the code.
Home.blade.php
@foreach ($users as $user) {
<tbody>
<tr>
<td>{{ $user->name }}</td>
</tr>
</tbody>
@endforeach
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
class UserController extends Controller
{
public function index()
{
$users = DB::table('users')->get();
return view()-> with ('home', ['users' => $users]);
}
}
I want to have a list, but it gives me an error code stated above.
Upvotes: 0
Views: 11151
Reputation: 11461
Adding to @LucasPiazzi's answer.
class UserController extends Controller
{
public function index()
{
$users = DB::table('users')->get();
return view('home')->with(['users' => $users]); //take a closer look here
}
}
This is how you pass a variable to a view from controller. now if you add a {{ dd($users) }}
to the home.blade.php
you should be able to see a dump of the the $users
variable
Upvotes: 0
Reputation: 2636
Try this:
use App\User;
class UserController extends Controller
{
public function index()
{
$users = User::all();
return view('home', compact('users'));
}
}
And in your view
@foreach($users as $user)
{{$user->name}}
@endforeach
Upvotes: 3