TechAttax TechAttax - 2 months ago 9
HTML Question

"Undefined variable: users" when trying to use @foreach

I am trying to make foreach loop in laravel to list all users but when I use the code that laravel suggested I get this error:

Undefined variable: users (View: /home/vagrant/Code/SimFly/resources/views/profile.blade.php)


The code causing the error is:

@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach


Please can someone help me.

Answer

To use users variable in a view you need to pass it from a controller first:

$users = User::all();
return view('profile', compact('users'));
Comments