[英]Get all users by specific role in laravel rest api
這是控制器中的索引功能,我想從數據庫中獲取所有具有特定角色的用戶。
此函數返回所有用戶,我添加了一個條件來按角色獲取用戶,但它不起作用。
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(string $role)
{
$users= User::all();
if($users->role == 'admin'){
return response()->json($users);
}
}
public function index(string $role)
{
$users= User::where('role','admin')->get();
return response()->json($users);
}
這是您可以通過特定角色獲取所有用戶的方式。
// Get all user of a specific role
$users = \App\User::query()->whereHas('roles', function ($query) {
$query->where('name', 'isAdmin');
})->get();
return response()->json($users);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.