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


Invalid argument supplied for foreach() in Laravel 5.1

一切正常,我不知道发生了什么事。我得到这个错误:

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

我试图获得附加到像这样的帖子的标签@foreach($post->tags as $tag)如果我做var_dump然后它说string(0)""如果我用@if(is_array($post->tags))这样做-没有错误,没有标签。我不知道问题出在哪里,因为这些分类都是按照同样的原则进行的,而且它们工作得很好。

这是Post.php模型代码:

public function tags()
{
    return $this->belongsToMany('App'Tag');
}
public function getTagListAttribute()
{
    return $this->tags->lists('id')->all();
}
这是Tag.php模型代码:
public function post()
{
    return $this->belongsToMany('App'Post');
}

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

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

请在给出无效的答案之前查看官方文档

如果没有标记,则$post->tags为空,因此@foreach($post->tags as $tag)将抛出一个错误。

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

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

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