I am very new to Laravel and PHP, just trying to list all users in my view file like this:
@foreach ($users as $user)
<li>{{ link_to("/users/{$user->username}", $user->username) }}</li>
@endforeach
But getting an error which says 'Invalid argument supplied for foreach()'
In my controller, I have the following function:
public function users() {
$user = User::all();
return View::make('users.index', ['users' => '$users']);
}
What am I doing wrong?
$users
is not defined in your controller, but $user
is. You are trying to @foreach
over a variable that literally equals the string '$users'
. Change:
$user = User::all();
to:
$users = User::all();
And remove the single quotes around $users
:
return View::make('users.index', ['users' => $users]);
The answer above is correct, but since others may have the same error (which basically means that the variable you have supplied to foreach is not an array) in a different context, let me give this as another cause:
- When you have an eloquent relationship (probably a hasMany) which has the same name as a fieldin that eloquent model, and you want to loop through the items in the relationship using a foreach. You will think you are looping through the relationship yet Laravel is treating the field as having a higher precedence than the relationship. Solution is to rename your relationship (or field, whatever the case).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With