Laravelでカテゴリーごとにレシピの数をCountしたい
解決したいこと
カテゴリー毎にレシピの数を表示させたい
サイドバーにカテゴリー一覧を作り、カテゴリー名の横にそのカテゴリーのレシピが何件あるのかを表示したいです。
各ソースコード
ResipeController
$categories = Category::all();
$category_count = Category::withCount('recipes')->take(5)->get();
Category.php
public function recipes()
{
return $this->hasMany('App\Recipe');
}
index.blade.php
<aside class="aside col-3">
<div class="widget">
<span class="widget_title">CATEGORY</span>
<ul>
@foreach($categories as $category)
<li><a href="">{{ $category->name }}</a><span>{{$category_count}}</span></li>
@endforeach
</ul>
</div>
</aside>
0 likes