Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ElMorin's avatar

How to count models if it's attach to specific model (Many to Many)

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.

0 likes
2 replies
ElMorin's avatar

Actually, at the moment I use count(), the collections is already done.


$cars = Car::where('dealer_id', $dealer->id)
                                    ->with('dealer')
                                    ->with('dealer.brands')
                                    ->get();

Then I do some calculation. Actually I can manage to do what I need this way :

$count = 0;
foreach ($cars as $car) {
    foreach ($car->dealer->brands as $brand) {
        if ($car->brand_id == $brand->id) {
            $count++;
        }
    }
}

I echo the $count value, but I have to do it many times and I was wondering if there was a way to do it in a more efficient way using Laravel method.

Please or to participate in this conversation.