foreach() 参数必须是数组|对象类型,给定的字符串
foreach() argument must be of type array|object, string given
我是 laravel 的新手,我对 foreach() blade 指令有一个奇怪的问题。
问题是当我想遍历一个集合时它抛出一个错误并说:
foreach() argument must be of type array|object, string given
但我已经使用 print_r() 方法打印了集合,并且该变量不包含任何字符串,它包含一个集合对象。
这是在到达 foreach 指令时抛出错误的代码段:
<section class="col-span-8 col-start-5 mt-10 space-y-6">
{{print_r($post->comments)}}
@foreach($post->comments as $comment) // here
<x-post-comment :comment="$comment"></x-post-comment>
@endforeach
</section>
基本上,在上面的 foreach 代码中,我有一个 Eloquent 关系,在 Post 和 Comment Models 之间,这种关系在 tinker 中工作得很好,但这里说它不是集合或数组。另外,我有一个 post-comment blade 组件,它在 foreach 中呈现评论的布局。
也就是每个post和它的注释之间关系的实现:
function comments()
{
return $this->hasMany(Comment::class);
}
正如我提到的,上述关系非常完美,但我不知道它有什么问题。
如有任何帮助,我们将不胜感激!
问题出在 <x-post-comment>
组件内部,我正在编写 @props('comment')
而不是 @props(['comment'])
所以,我缺少 'comment' 周围的方括号。
错误消息是关于 foreach 而不是 props 这就是为什么我一直在考虑 foreach 部分的原因。
(@Yassin 在评论中回答)
我是 laravel 的新手,我对 foreach() blade 指令有一个奇怪的问题。 问题是当我想遍历一个集合时它抛出一个错误并说:
foreach() argument must be of type array|object, string given
但我已经使用 print_r() 方法打印了集合,并且该变量不包含任何字符串,它包含一个集合对象。
这是在到达 foreach 指令时抛出错误的代码段:
<section class="col-span-8 col-start-5 mt-10 space-y-6">
{{print_r($post->comments)}}
@foreach($post->comments as $comment) // here
<x-post-comment :comment="$comment"></x-post-comment>
@endforeach
</section>
基本上,在上面的 foreach 代码中,我有一个 Eloquent 关系,在 Post 和 Comment Models 之间,这种关系在 tinker 中工作得很好,但这里说它不是集合或数组。另外,我有一个 post-comment blade 组件,它在 foreach 中呈现评论的布局。
也就是每个post和它的注释之间关系的实现:
function comments()
{
return $this->hasMany(Comment::class);
}
正如我提到的,上述关系非常完美,但我不知道它有什么问题。
如有任何帮助,我们将不胜感激!
问题出在 <x-post-comment>
组件内部,我正在编写 @props('comment')
而不是 @props(['comment'])
所以,我缺少 'comment' 周围的方括号。
错误消息是关于 foreach 而不是 props 这就是为什么我一直在考虑 foreach 部分的原因。
(@Yassin 在评论中回答)