1 year ago

Select Users that have only 1 Role

Posted 1 year ago by Notdavis

I have the classic setup of Users and Roles, where Users can have many Roles, and Roles can have many Users:

On the User model: public function roles() { return $this->belongsToMany('App\Models\Role')->withTimestamps(); }

On the Role model: public function users() { return $this->belongsToMany('App\Models\User'); }

Currently it's easy to generate a list of users where they have a Role, e.g.

$users = User::whereHas('roles', function ($query) {
            $query->where('name', 'TheRoleName');

But I want to limit Users I send to a view to Users who have only 'TheRoleName' and don't also belong to 'AnotherRoleName', and it's become a little complicated.

I have tried Role::with('users')->where('name', 'TheRoleName')->get()

But haven't quite worked out how to get a collection of Users from that to send to the view which uses methods on the Users model

Please sign in or create an account to participate in this conversation.