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

king_eke's avatar

Group and Count a relationships relationship

I want to group this relationship by another relationship and instead of getting the collection i want to get the number of collections, that's how many they are

The client model where has the delivery relationship

public function deliveries(){
        return $this->hasMany('App\Delivery');
 }

The delivery model where has the status relationship

 public function status(){
        return $this->hasOne('App\DeliveryStatus');
   }

what i've done in the client model so i can just call it anywhere

public function countDeliveries(){
        return $this->deliveries()->get()->groupBy('status.status');
 }

it works, but it returns the whole collections with all their attributes, i want to know how many they are that's all, i don't need all their data.

this is what i get

Collection {#33353 ▼
  #items: array:3 [▼
    "Delivered" => Collection {#2858 ▶}
    "Failed" => Collection {#5379 ▶}
    "Cancelled" => Collection {#26800 ▶}
  ]
}

0 likes
4 replies
nouveaucode's avatar
public function countDeliveries(){
        return $this->deliveries()->count();
 }

or perhaps

public function countDeliveries(){
        return $this->deliveries->count();  // no parenthesis after deliveries
 }
king_eke's avatar

@nouveaucode the parenthesis makes it load faster than without it, assuming the database has over 5k records,

asides that, I want them grouped by the delivery status of each delivery

king_eke's avatar
king_eke
OP
Best Answer
Level 1

As usual i'm the one who solves my questions on here,

Anyone facing this, this is how i solved it, DB::raw is really powerful and fast.


return DeliveryStatus::whereHas('delivery', function($q) use($client_id){
            $q->where('client_id', $client_id);
        })->select('status', DB::raw('count(*) as total'))->groupBy('status')->pluck('total','status')->all();

Please or to participate in this conversation.