0

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.

GregorChristie
  • 1,183
  • 2
  • 8
  • 7
  • Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Henders Sep 16 '16 at 15:13
  • Can you show us your function? – twoam Sep 16 '16 at 15:14
  • 3
    That error message is crystal clear. `$users` is not defined in that scope. How do you think _we_ can help with that? – arkascha Sep 16 '16 at 15:16

3 Answers3

3

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

$users = User::all();
return view('profile', compact('users'));
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

Its also a great practice to check state (isset, count for example) of the array/variable before looping through it, to protect any unforeseen errors.

olli3
  • 11
  • 2
0

As per the suggestions above, the problem is that the view was not being passed the variable.

To catch this in the blade template use something like a @forelse instead of a @foreach

ProfileController

$users = User::all();
return view('profile', [
    'users' => $users
]);

Profile Blade

@forelse
    <p>This is user {{ $user->id }}</p>
@empty
    <p>There are no users</p>
@endforelse
Spholt
  • 3,724
  • 1
  • 18
  • 29