In my project I have a users table, a roles table and a pivot table role_user, which defines which is the role of every user.
Of course there are corresponding models, User and Role.
Now, I would like to have a Client model, which will load only the users that have the role of Client. (role_id = 4).
Is that possible and how can I do it?
User::clients()->get();
//on model
public function scopeClients($query)
{
return $query->whereHas('role', function (Builder $subquery) {
$subquery->where('role'_id, 4);
});
}
Thank you, @sinnbeck. That seems like a good idea. I thought it would be nice to use Client::whatever_function when referring to clients. Is that possible with scope?
but when I call Client::all() the query is wrong, because instead of looking for user_role table, its is looking for client_role. The query is
select * from `users` where exists (select * from `roles` inner join `client_role` on `roles`.`id` = `client_role`.`role_id` where `users`.`id` = `client_role`.`client_id` and `role_id` = 4))