I have an eloquent model User which is in 1:N relation with itself (a single user can refer multiple users, and a single user can be referred by a single user only).
/*
* Get the user's referrals
*/
public function referrals()
{
return $this->belongsToMany('App\User');
}
/*
* Get the referred user's parent referral
*/
public function parentReferral()
{
return $this->belongsTo('App\User');
}
Does Laravel provide a native method that will count all the belongsToMany relations?
(A simple way I can do this is just get the parent user's id and manually count all the appearances, but I wish to know if there's a method given by Laravel that I can use on the object)
Use the withCount()
method to count the number of results from a relationship:
If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models
User::withCount('referrals')->get();