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>
Enjoyed This Tip?
Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.
Recent Courses
How to Build Laravel 12 API From Scratch
28 lessons
1 h 21 min
Laravel 12 For Beginners: Your First Project
15 lessons
1 h 32 min
Claude Code for Laravel Projects: Crash Course
8 lessons
48 min