Home > Software engineering >  Laravel Eloquent - Return Users with specific role (many-to-many relationship)
Laravel Eloquent - Return Users with specific role (many-to-many relationship)

Time:12-02

I have an application where I want to find all the users (from a specified client) with a certain role (in this case Super Admin)

A client can have many users

public function users() {
    return $this->hasMany(User::class);
}

A user can belong to many roles

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

I want to be able to return all the users from a client with a specific role.

So in the Client Model I want something like:

public function superAdmins() {
    return ... // NOT SURE WHAT TO PUT HERE
}

CodePudding user response:

When defining relations you can add where() statements as well.

This means you can use whereHas:

public function superAdmins() {
    return $this->hasMany(User::class)
              ->whereHas('roles', function($query) {
                  return $query->where('name', 'super');
              });
}
  • Related