Home > Software design >  Get all users by specific role in laravel rest api
Get all users by specific role in laravel rest api

Time:07-24

This is the index function in controller, I want to get all users from the database that have a specific role.

This function returns all users, I have added a condition to get users by role but it doesn't work.

 /**
 * 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);
     }
    
}

CodePudding user response:

public function index(string $role)
{
     $users= User::where('role','admin')->get();

     return response()->json($users); 
}

CodePudding user response:

This is how you can get all user by a specific role.

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

return response()->json($users);
  • Related