public function countDeliveries(){
return $this->deliveries()->count();
}
or perhaps
public function countDeliveries(){
return $this->deliveries->count(); // no parenthesis after deliveries
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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 ▶}
]
}
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.