Reputation: 733
I have three roles: 1. Admin
2. Client
3. Store
I have three tables: 1. users
2. roles
3.role_user
How can I get all users who have the role Client
?
I tried this
$clients = User::roles()->where('App\Models\Role',Role::CLIENT)->get();
I'm getting following error.
Non-static method App\Models\User::roles() should not be called statically
Role Model
class Role extends Model
{
public const ADMIN = 'Admin';
public const CLIENT = 'Client';
public const STORE = 'Store';
public function users()
{
return $this->belongsToMany('App\Models\User')->using('App\Models\UserRole');
}
}
User Model
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name',
'first_name',
'last_name',
'email',
'password',
'activated',
'token',
'signup_ip_address',
'signup_confirmation_ip_address',
'signup_sm_ip_address',
'admin_ip_address',
'updated_ip_address',
'deleted_ip_address',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function hasRole(String $roleName)
{
return $this->roles()->where('name', $roleName)->exists();
}
public function roles()
{
return $this->belongsToMany('App\Models\Role');
}
public function addRole(String $roleName)
{
$role = Role::where('name', $roleName)->first();
if ($role) $this->roles()->save($role);
}
}
Upvotes: 1
Views: 3625
Reputation: 11034
That's because you're trying to call the roles
method on the Model class and not the instance, here's how it should be
$clients = Role::whereName('client')->first()->users;
Upvotes: 3
Reputation: 17206
You can do it with whereHas()
method. it's a way to condition on relation using exists
in query
$clients = User::whereHas('roles', function($role) {
$role->where('name', '=', Role::CLIENT);
})->get();
If you want to get the role too, stack the with()
method
$clients = User::whereHas('roles', function($role) {
$role->where('name', '=', Role::CLIENT);
})->with(['roles' => function($role) {
$role->where('name', '=', Role::CLIENT);
}])->get();
Upvotes: 5