Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

craigwillis's avatar

Many to many relationships

Hi

I have 3 tables:

groups:
id, name

group_members:
id, group_id, user_id

users:
id

Now, what I'm looking to do, is to get all of the groups (just the groups), that have members associated with them so, for instance i have the following:

groups
1, test
2, test-1
3, test-2

group_members
1, 1, 1
2, 1, 2
3, 3, 1

users
1
2

If I want to get all groups that user with id = 1 belongs to, it should return:

groups
1, test
3, test-2

Is there a way in eloquent that i can just return the groups (in a collection)

Thanks

0 likes
2 replies
bobbybouwmann's avatar

You can probably do something like this

$userId = 1;

$groups = Group::whereHas('users', function ($query) use ($userId) {
    $query->where('user_id', $userId);
})->get();
craigwillis's avatar

Had to change users to be members, but it works great

Thanks!

Please or to participate in this conversation.