Try something like that :
$users = User::whereHas('roles', function ($q) {
$q->whereNotIn('roles.id', Role::where('id', '!=', 1)->lists('id'));
})->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello,
i have 3 tables:
users:
| id | group_id |
| --- | -------- |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 2 |
| 6 | 3 |
| 7 | 2 |
user_role:
| user_id | role_id |
| ------- | ------- |
| 1 | 1 |
| 2 | 3 |
| 4 | 2 |
roles:
| id | group_id |
| --- | -------- |
| 1 | 1 |
| 2 | 3 |
| 3 | 1 |
and now i want for example all users with group_id 1 who have no assignment to any group of group_id = 1
in my example, i want get the user with id = 3 and user with id = 4, cause they are not in role = 1 or role = 3.
I hope anyone understand me an could help me with this query?
$users = User::where('group_id', '=', $group_id)->has('roles', '=', 0)->get();
Roles in the has is the name of the function defining the belongsToMany relationship with roles.
Check http://laravel.com/docs/5.0/eloquent#querying-relations
Please or to participate in this conversation.