@ElMorin is withCount() what you're looking for?
https://laravel.com/docs/5.5/eloquent-relationships#counting-related-models
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I got 3 tables. Dealers, Cars and Brands. Each cars belongsTo a dealer and a brand. Each dealer hasMany cars and hasMany a brand or multiple brands. Each brand hasMany cars and hasMany dealers.
So, the relationship between car_dealers is one to many. The relationship between car_brands is one to many. The relationship between dealers_brands is many to many.
I'm trying to build a query where I could count the number of cars related to the dealer's brands.
In the past, each dealers was related to one brand, so there was the query :
$cars->where('car_brand_id', $dealer->brand_id)->count();
Actually, the only issue I find is to do a count for each related brand to the dealer. Maybe I could do a specific scope.
Is there a way I could do something in eloquent fundamentals like :
$cars->where('car_brand_id' $dealer->brands()->id)->count();
This way, it will count the car if the dealer is related to the car_brand_id.
Please or to participate in this conversation.