php Laravel @foreach - 提供的参数无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22393986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:53:33  来源:igfitidea点击:

Laravel @foreach - invalid argument supplied

phplaravel

提问by Adnan Khan

I am very new to Laravel and PHP, just trying to list all users in my view file like this:

我对 Laravel 和 PHP 非常陌生,只是想像这样在我的视图文件中列出所有用户:

@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()'

但是收到一个错误,上面写着“为 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?

我究竟做错了什么?

回答by Jeff Lambert

$usersis not defined in your controller, but $useris. You are trying to @foreachover a variable that literally equals the string '$users'. Change:

$users没有在您的控制器中定义,但是$user。您正在尝试@foreach覆盖一个字面上等于 string 的变量'$users'。改变:

$user = User::all();

to:

到:

$users = User::all();

And remove the single quotes around $users:

并删除周围的单引号$users

return View::make('users.index', ['users' => $users]);

回答by gthuo

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:

上面的答案是正确的,但由于其他人在不同的上下文中可能有相同的错误(这基本上意味着您提供给 foreach 的变量不是数组),让我将此作为另一个原因:

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

- 当您有一个与该 eloquent 模型中的字段同名的 eloquent 关系(可能是 hasMany),并且您想使用 foreach 遍历关系中的项目时。你会认为你正在遍历关系,但 Laravel 将字段视为比关系具有更高的优先级。解决方案是重命名您的关系(或字段,无论如何)。