Olaszka Olaszka - 2 months ago 43
MySQL Question

Laravel count Eloquent belongsToMany related model

I'm new to Laravel, and I got stuck with the following issue:
I have a table for the users, and groups, and a table for connecting them. The general task any user can join any group.

----------------------------------------------
| users | groups | user_groups |
|--------------------------------------------|
| id - int pk | id - pk | id - pk |
| name text | name | user_id - fk |
| email | | group_id - fk |
| phone | | any_attr |
----------------------------------------------


I have the following models:

class User
{
...
public function groups()
{
return $this->belongsToMany(Group::class, 'user_groups')->withPivot(['is_notification_requested']);
}
...
}


class Group
{
...
public function users()
{
return $this->belongsToMany(User::class, 'user_groups');
}
...
}


How do I get all of the groups, with a count of the members? I need the Group model, and a count of the users in the group.

Answer

If you're using Laravel 5.3, you can simply add withCount('relationship') as documented here: https://laravel.com/docs/5.3/eloquent-relationships#counting-related-models

Here's an example following your code:

$groups = Group::withCount('users')->get();

Now you can do this:

foreach($groups as $group) {
    echo $group->user_count
}