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:
- Projects have many Groups
- 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!