在 Laravel 5.1 中为 foreach() 提供的参数无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32943844/
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-09-14 12:27:08  来源:igfitidea点击:

Invalid argument supplied for foreach() in Laravel 5.1

phplaravelforeach

提问by zlotte

Everything was working fine and I don't know what happened. I'm getting this error:

一切正常,我不知道发生了什么。我收到此错误:

Invalid argument supplied for foreach().

为 foreach() 提供的参数无效。

I'm trying to get tags that are attached to post like this @foreach($post->tags as $tag)If I do var_dumpthen it says string(0)""if I do this with @if(is_array($post->tags))- no error and no tags. I don't know where the problem is because the categories are made in the same principle and they are working fine.

我正在尝试获取像这样附加到帖子的标签@foreach($post->tags as $tag)如果我这样做了,var_dump那么它会说string(0)""我是否这样做@if(is_array($post->tags))- 没有错误,也没有标签。我不知道问题出在哪里,因为类别是按照相同的原则制作的,并且它们工作正常。

This is Post.php model code:

这是 Post.php 模型代码:

public function tags()
{
    return $this->belongsToMany('App\Tag');
}

public function getTagListAttribute()
{
    return $this->tags->lists('id')->all();
}

This is Tag.php model code:

这是 Tag.php 模型代码:

public function post()
{
    return $this->belongsToMany('App\Post');
}

回答by cre8

There is a simple call you can use for this case:

对于这种情况,您可以使用一个简单的调用:

@forelse($users as $user)
 <li>{{ $user->name }}</li> 
@empty 
<p>No users</p> 
@endforelse

Please check the official documentation before you give inefficient answers.

在您给出低效的答案之前,请检查官方文档。

回答by P??

If there are no tags then $post->tagsis empty and therefor @foreach($post->tags as $tag)will throw an error.

如果没有标签,$post->tags则为空,因此 @foreach($post->tags as $tag)将引发错误。

You can check with @if(!empty($post->tags)):before the foreachif there are tags for this post or not to avoid a error message.

您可以@if(!empty($post->tags)):foreach此帖子是否有标签之前检查,以避免出现错误消息。

If there should be tags for this post but there aren't any then your $post->tagsis not filled with data correctly.

如果这篇文章应该有标签但没有标签,那么你的$post->tags数据没有正确填充。

回答by Dzung Cao

when your array is empty, contains no element, foreachwill throw that exception. For safety you can use normal for(....)instead.

当您的数组为空,不包含任何元素时,foreach将抛出该异常。为了安全起见,您可以使用 normal for(....)代替。