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

saqueib's avatar

Get all users which dont have admin role in belongsToMany relation

I want to get all user which don't have admin role, it's a belongsToMany relation where a user can have many roles. I want to get only the user who is not an admin.

I have tried following but it gives me users nested in each role, I want it a list of users limit(5) as a collection.

return Role::with('users')->where('name', '!=', 'admin')->get();

here is table structure-

users
- id
- name
- email

roles
- id
- name

role_user
- user_id
- role_id

Any way to do it?

0 likes
3 replies
tisuchi's avatar

I dont know anything about your user's table structure. I assume that, there is a table column name admintype where you store user role id / type name.

So, just simply try-

return User::with('role')->where('usertype', '!=', 'admin')->get();
1 like
saqueib's avatar

@tisuchi updated my question with table, unfortunately, your solution doesn't work.

saqueib's avatar
saqueib
OP
Best Answer
Level 2

found it

$users = User::whereDoesntHave('roles', function ($q) {
    $q->where('name', 'admin');
})->limit(5)->get()
1 like

Please or to participate in this conversation.