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

TomasAm's avatar

Get roles which does not belong to a specific user id

I am trying to foreach in blade multiselect all roles related to the user, this is easy to do due to relation, but I want also to foreach the rest not related roles to the user.

I try to use this controller:

$roles = Role::doesntHave('users')->get();

but it returns only users which are not linked with any roles at all, so how do I specify that it should return roles which are not related to a specific user which id comes with the controller request

 public function edit($id) {
 $roles = Role::doesntHave('users')->get();
....
}

users and roles are linked via pivot table many to many relation.

0 likes
1 reply
Ksandar's avatar
Ksandar
Best Answer
Level 26

@tomasam you can try this

public function edit($id) {
  $roles = Role:: whereDoesntHave('users', function($query) use($id) {
    $query->where('user_id', $id);
  })->get();
  ....
}
1 like

Please or to participate in this conversation.