TechAttax TechAttax - 1 year ago 59
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>

Please can someone help me.

Answer Source

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

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