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
class HomeController extend Controller{ public function index() { $categories = Category::query() ->whereNull('category_id') ->with(['subcategories.subcategories' => function($query) { $query->withCount('products'); }])->get(); }}
class Category extends Model{ public function subcategories() { return $this->hasMany(Category::class); } public function products() { return $this->hasMany(Product::class); }}
<ul> @foreach($categories as $category) <li> {{ $category->name }} @if ($category->subcategories) <ul> @foreach($category->subcategories as $subcategory) <li> {{ $subcategory->name }} @if ($subcategory->subcategories) <ul> @foreach ($subcategory->subcategories as $subcategory) <li>{{ $subcategory->name }} ({{ $subcategory->product_count }})</li> @endforeach </ul> @endif </li> @endforeach </ul> @endif </li> @endforeach</ul>