Adnan Khan
Adnan Khan

Reputation: 665

Laravel @foreach - invalid argument supplied

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?

Upvotes: 8

Views: 79618

Answers (3)

eliyas yari
eliyas yari

Reputation: 28

Code:

foreach ($allresults as $key => $vl) {
    foreach ($vl as $vll) {
        print_r($vll->customerid);
    }
}

Shows error "Invalid argument supplied for foreach()",
but after add line break, it working:

foreach ($allresults as $key => $vl) {
    foreach ($vl as $vll) {
        print_r($vll->customerid);
    }
    break;
}

Upvotes: 0

gthuo
gthuo

Reputation: 2566

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

Upvotes: 5

Jeff Lambert
Jeff Lambert

Reputation: 24671

$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]);

Upvotes: 15

Related Questions