return User::where(function($query) use ($roleId) {
$query->whereDoesntHave('roles', function ($query) use ($roleId) {
$query->where('id', $roleId);
})->orWhereDoesntHave('roles');
})->get();
I think that should work but haven't tested it :)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Sorry if my question is a bit confusing because I'm not a native speaker.
So the question is I have a User and a Role model, I'm trying to display a list of users that doesn't have any roles assigned to it, or the user that don't have this specific role.
The relation is many to many and using a pivot table
I tried to write this method on my model file
public function getUsersNotInRole($id)
{
return User::with('roles')->where('roles.id, '!=', $id)->orWhere('roles.id', '')->get();
}
but didn't get the result I expected, any insight please?
Please or to participate in this conversation.