我正在处理我的应用程序的博客部分,我想显示每个类别中的帖子总数。我对 Laravel 很陌生。我在控制器和刀片视图中编写了一些代码,但出现错误
在 null 上调用成员函数 count()
请帮忙,谢谢。
在我的控制器中:
public function post($slug){
$post = Post::with('category', 'user')->where('slug', $slug)->first();
$posts = Post::with('category', 'user')->inRandomOrder()->limit(3)->get();
$categories = Category::all();
$tags = Tag::all();
if($post){
return view('website.post', compact(['post', 'posts', 'categories', 'tags']));
}else {
return redirect('/');
}
}
在我要显示帖子计数的“我的视图”中:
<div class="sidebar-box">
<h3 class="heading">Categories</h3>
<ul class="categories">
@foreach($categories as $category)
<li><a href="{{ route('website.category', ['slug' => $category->slug]) }}">{{ $category->name }}
<span>{{ $category->posts->count() }}</span> </a></li>
@endforeach
</ul>
</div>