2

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)

1 Answer 1

3

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(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, search myself but couldn't find it in the documentation for some reason :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.