In my Laravel
implemented web application i have Users
and Roles
tables with models which they are ManyToMany
.
i want to get all users which they have specific role, for example:
$users = User::with(['roles' => function ($query) {
$query->whereLabel('is-portal-manager');
}])->get();
unfortunately this code return all users and compare role
label and return that in relation ship array
Illuminate\Database\Eloquent\Collection {#2069 ▼
#items: array:3 [▼
0 => App\User {#2076 ▼
...
#relations: array:4 [▼
"properties" => null
"child" => Illuminate\Database\Eloquent\Collection {#2073 ▶}
"parent" => null
"roles" => Illuminate\Database\Eloquent\Collection {#2087 ▼
#items: array:1 [▼
0 => App\Entities\Role {#2074 ▼
...
#attributes: array:5 [▼
"id" => 1
...
"label" => "is-portal-manager"
...
]
...
}
]
}
]
...
}
1 => App\User {#2077 ▼
...
#relations: array:4 [▼
"roles" => Illuminate\Database\Eloquent\Collection {#2093 ▼
#items: []
}
]
...
}
]
}
as you can see in above output second user doesn't have any role and #items: []
is empty. i don't need to have this output structure and i want to have only which users have specific role
, not all users with empty
roles. second item of this collection shouldn't this output
My Answer:
> You can achieve this by using the `whereHas` method in Laravel to filter users based on their roles. Here's an example code snippet to get all users with a specific role:
php
$role = 'admin'; // Specify the role you want to filter by
$users = User::whereHas('roles', function ($query) use ($role) {
$query->where('name', $role);
})->get();
// You can also eager load the roles relationship if needed
$users = User::whereHas('roles', function ($query) use ($role) {
$query->where('name', $role);
})->with('roles')->get();
In this code snippet, we are using the `whereHas` method to filter users based on their roles. We are passing a closure function to the `whereHas` method to specify the condition for filtering users with a specific role. You can replace `'admin'` with the role name you want to filter by.
This will return a collection of users who have the specified role.
Rate this post
4 of 5 based on 6387 votesComments