ST80
ST80

Reputation: 3903

Laravel how to get users by roles dynamically from api endpoint

How can I get the users based on which role they have in laravel? I have roles like for example "admin", "author", "editor" and I want to have a dynamic api-endpoint.

so in my api.php I have:

Route::get('users/{role}', "Api\UserController@role");

and my Controller looks like this:

public function show()
{
    $user_role = User::whereHas(
        'roles',
        function ($q) {
            $q->where('name', 'admin');
        }
    )->get();

    return $user_role;
}

This works fine so far, but I want the endpoint to be dynamic, like if want all my editor users the endpoint should be api/users/editors etc. etc.

How can I achieve this?

Upvotes: 0

Views: 696

Answers (2)

Ali Jawadi
Ali Jawadi

Reputation: 131

Your controller function should look like this:

public function show(Role $role)
{
    $users = $role->users;

    return $users;
}

And your Role Eloquent Model should have these methods:

public function users()
{
   return $this->belongsToMany(User::class, 'user_role')
}

public function getRouteKeyName()
{
    return 'name';
}

Upvotes: 1

Kuldeep Mishra
Kuldeep Mishra

Reputation: 4040

public function show($role) //example: $role = 'admin'
{
    return User::whereHas('roles', function ($q) use ($role) {
        $q->where('name', $role);
    })->get();
}

Upvotes: 1

Related Questions