php - I want to select all Users which are not members of a Group with id=6
My tables
- users
id | name |
---|---|
Cell 1 | Cell 2 |
Cell 3 | Cell 4 |
Answer
Solution:
If you want to select users who don't have a relation, you can use whereDoesntHave:
$users = User
::whereDoesntHave('groups', fn($query) => $query->where('id', 1))
->get();
In this case I'm querying for all users who dont have a group with id 1 linked.
Answer
Solution:
public function show(Group $group)
{
//Fetching all members of the group
$exceptId = $group->users()->pluck('users.id');
return Inertia::render('Clients/Show', [
//Here it will fetch all users except those with ids matching $exceptId array
'users' => Group::whereNotIn('id', $exceptId)->get(),
]);
}
Source