Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel @foreach - invalid argument supplied

Tags:

php

laravel

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?

like image 699
Adnan Khan Avatar asked Mar 14 '14 00:03

Adnan Khan


2 Answers

$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]);
like image 57
Jeff Lambert Avatar answered Oct 22 '22 13:10

Jeff Lambert


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).

like image 30
gthuo Avatar answered Oct 22 '22 11:10

gthuo