所以我正在制作一個博客網站并實施標簽。我不斷收到標題中的錯誤,并且不確定我應該做什么。我在這里查看了類似的問題,但它們看起來與我的做法不同。我使用數據透視表作為標簽。當我只對帖子進行操作時,它運行良好,并顯示這里的所有內容是我的帖子控制器的索引方法。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';}
1 回答

Smart貓小萌
TA貢獻1911條經驗 獲得超7個贊
錯誤
您的錯誤來自于 foreach 循環中的變量$post已作為非對象返回。
可能的原因
這$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
- 1 回答
- 0 關注
- 149 瀏覽
添加回答
舉報
0/150
提交
取消