Laravel count nested many to many relationship

Viewed 32

I feel this should be pretty straight forward, but I can't seem to find the answers online...

I'm working on a Laravel 9 API project and I have the below relationships:

  1. Projects have many Groups
  2. Groups have a many to many relationship with Users using a pivot table called GroupUser

What I'm trying to do is get the count of all Users associated with a specific Project through each group, but I just want them in one combined list. For example:

A Project has 2 Groups, each of which have 3 Users, so the output would be a 6 Users, and I don't care about the same user being included in both groups and counted twice.

I've tried using the below in the Project model:

public function users()
{
     return $this->hasManyThrough(User::class, Group::class)
}

But this seems to only work if the Group -> User relationship is a hasMany, but its a belongsToMany because of the pivot table.

Ideally I want to be able to access the count in a resource like this:

$project->users()->count()

Any ideas how I would go about getting this to work?

Thanks in advance!

1 Answers

Because Laravel doesn't solve a belongsToThrough relationship natively, someone has made a package to support the funcionality: https://github.com/staudenmeir/belongs-to-through

As you can see from the 713 stars on GitHub it is quite popular.

That way you can define nested belongsTo relationships - and it actually supports infinitely deep relationships

Related