3-level structure of parent-children

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 @endforeach
15 </ul>
16 @endif
17 </li>
18 @endforeach
19 </ul>
20 @endif
21 </li>
22 @endforeach
23</ul>

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord