So, I have User and Role models with many-to-many relationships, I have 3 roles: super , admin and moderator with 4 users who say: John , Mike , James and Larry .
John is super , Mike has admin and moderator roles, James is admin , and Larry is moderator . To display users who do not have specific roles, I created this area:
public function scopeDoesntHaveRoles($query, $roles = [], $column = 'id') { return $query->whereDoesntHave('roles')->orWhereHas('roles', function ($q) use ($roles, $column) { $q->whereNotIn($column, $roles); }); }
When I call User::doesntHaveRoles([1])->lists('name', 'id') to get users who don't have the super role, it works and returns:
{"2":"Mike","3":"James","4":"Larry"}
But when I try to list users who do not have admin role User::doesntHaveRoles([2])->lists('name', 'id') , yes James does not appear there, but Mike appears when he actually has a role admin :
{"1":"John","2":"Mike","4":"Larry"}
I think because Mike also has a moderator role, do you see something wrong in my area? or do you have other solutions?
thanks
Edit: Here is my summary diagram
Schema::create('user_roles', function (Blueprint $table) { $table->integer('user_id')->unsigned(); $table->integer('role_id')->unsigned(); $table->primary([ 'user_id', 'role_id' ]); });
User model
public function roles() { return $this->belongsToMany(Role::class, 'user_roles'); }
Role Model
public function users() { return $this->belongsToMany(User::class, 'user_roles'); }