If you have a 3-level structure of parent-children, like categories in an e-shop, and you want to show the number of products on the third level, you can use with('yyy.yyy')
and then add withCount()
as a condition
1class HomeController extend Controller 2{ 3 public function index() 4 { 5 $categories = Category::query() 6 ->whereNull('category_id') 7 ->with(['subcategories.subcategories' => function($query) { 8 $query->withCount('products'); 9 }])->get();10 }11}
1class Category extends Model 2{ 3 public function subcategories() 4 { 5 return $this->hasMany(Category::class); 6 } 7 8 public function products() 9 {10 return $this->hasMany(Product::class);11 }12}
1<ul> 2 @foreach($categories as $category) 3 <li> 4 {{ $category->name }} 5 @if ($category->subcategories) 6 <ul> 7 @foreach($category->subcategories as $subcategory) 8 <li> 9 {{ $subcategory->name }}10 @if ($subcategory->subcategories)11 <ul>12 @foreach ($subcategory->subcategories as $subcategory)13 <li>{{ $subcategory->name }} ({{ $subcategory->product_count }})</li>14 @endforeach15 </ul>16 @endif17 </li>18 @endforeach19 </ul>20 @endif21 </li>22 @endforeach23</ul>