代码之家  ›  专栏  ›  技术社区  ›  Dev

在laravel rest api中按特定角色获取所有用户

  •  0
  • Dev  · 技术社区  · 2 年前

    这个函数返回所有用户,我添加了一个条件以按角色获取用户,但它不起作用。

     /**
     * 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);
         }
        
    }
    
    2 回复  |  直到 2 年前
        1
  •  1
  •   kodemetrics    2 年前
    public function index(string $role)
    {
         $users= User::where('role','admin')->get();
    
         return response()->json($users); 
    }
    
        2
  •  0
  •   SaaberDev    2 年前

    这是通过特定角色获取所有用户的方式。

    // Get all user of a specific role
    $users = \App\User::query()->whereHas('roles', function ($query) {
        $query->where('name', 'isAdmin');
    })->get();
    
    return response()->json($users);