5

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.

Zoltán Fekete
  • 504
  • 1
  • 6
  • 22
  • Do you need the counting as an previously calculated attribute of the returning object or can it be calculated when you print the value? – Laerte Sep 26 '16 at 18:37
  • Are you using Laravel 5.2 or 5.3? – ollieread Sep 26 '16 at 19:52
  • **Laerte:** well, its nevermind when do I get the value. I just need a list of the groups, and the count of the users in the groups one by one. Its a paginated listing. **Ollieread:** Laravel 5.3 – Zoltán Fekete Sep 26 '16 at 19:58

1 Answers1

6

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
}
ollieread
  • 6,018
  • 1
  • 20
  • 36