Level 88
You can probably do something like this
$userId = 1;
$groups = Group::whereHas('users', function ($query) use ($userId) {
$query->where('user_id', $userId);
})->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
Please or to participate in this conversation.