skip to Main Content

I need to make an advanced query in Laravel hopefully using Eloquent to make that a collection but a query builder or raw normal SQL query is acceptable.

I have users table with User model having relation:

public function roles()
{
   return $this->belongsToMany(Role::class,'users_roles');
}

I have roles table, with Role model having relation:

public function users()
{
   return $this->belongsToMany(User::class,'users_roles');
}

So, I have users_roles table with columns [user_id, role_id], so I can have users with multiple roles

I want to get all users with roles different from a certain role, for example get all users that are all kind of roles except role of id 1

how to do that?

2

Answers


  1. You can pass a where clause to withWhereHas to defined rules on which models to return depending on relations, like so:

    $usersWhereRoleIsNotOne = User::query()
        ->withWhereHas('roles', function(Builder $builder){
            $builder->whereNot('id', 1);
        })
        ->get();
    
    Login or Signup to reply.
  2. You can use the whereDoesntHave method provided by Eloquent to achieve this.

    $roleId = 1; // the role you want to exclude
    
    $users = User::whereDoesntHave('roles', function ($query) use ($roleId) {
        $query->where('roles.id', $roleId);
    })->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search