因此,我正在建立一个博客网站,并正在实现标签。我一直在标题中收到错误,不确定我该怎么做。我在这里浏览了类似的问题,但它们看起来与我的做法不同。我在标签上使用数据透视表。当我对帖子进行处理时,它只能很好地工作并显示所有内容,这是我的帖子控制器中的index方法。
public function index()
{
$posts = Post::all()->sortByDesc('created_at');
return view('blogs.blogs', compact('posts'));
}
这是我的标签控制器的索引方法。
public function index(Tag $tag){
$posts = $tag->posts();
return view('blogs.blogs')->with('posts',$posts);
}
这是我在视图中输出的方式
@foreach($posts as $post)
<div class="well row">
<div class="col-md-4">
<img style="width: 100%" src="/storage/cover_images/{{$post->cover_image}}" alt="">
</div>
<div class="col-md-8">
<h3> <a href="/posts/{{$post->id}}">{{$post->title}}</a></h3>
<h3>{{$post->created_at}}</h3>
</div>
</div>
@endforeach
这是我的标签模型
public function posts() {
return $this->belongsToMany(Post::class);
}
public function getRouteKeyName()
{
return 'name';
}
错误
您的错误来自以下事实:$post
您的foreach循环中的变量已作为非对象返回。
可能的原因
那$posts
不是作为一个集合返回,而是一个查询构建器实例。
$posts = $tag->posts();
如果您在Tag
模型和Post
模型之间建立了雄辩的关系,那么当您将其作为方法(即$tag->posts()
)进行访问时,您将获得雄辩的查询构建器实例。如果您将此作为属性(即$tag->posts
)进行访问,它将返回一个雄辩的集合。
建议
尝试将帖子作为集合传递到视图
public function index(Tag $tag) {
return view('blogs.blogs', [
'posts' => $tag->posts
]);
}
并尝试使用@forelse
循环来捕获没有帖子的实例
@forelse ($posts as $post)
@empty
@endforelse
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句