Home > database >  Laravel : How to get count for eloquent relation
Laravel : How to get count for eloquent relation

Time:10-22

I have defined my relations in my models :

public function orders() {
    return $this->hasMany(Orders::class, 'user_id', 'id');
}   

How to get user with order count ?

CodePudding user response:

Use withCount for that:

$user = User::withCount('orders')->first();

https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models

  • Related