Laravel route accessible by two types of user

Asked

Viewed 144 times

0

I have an application where I have two authenticated user types (common and administrator). I have a route where I pass the id of the state and return me a json with the cities of that state. It turns out that I would like to keep this route available only for logged in users but for both types.

Route::get('{id}/cities', 'ApiControllers\StateController@cities')
->middleware('auth:admin', 'auth', 'verified')->name('cities');

I left my route file like this. When I access with an ordinary user, I am directed to the admins login screen. How do I make it accessible by any logged-in user (regardless of type)?

1 answer

1

You can pass your roles separated by comma and update the middleware to receive the parameters correctly.

Route::get('{id}/cities', 'ApiControllers\StateController@cities')
->middleware('auth:admin,verified')->name('cities');

And in your middleware, something like:

public function handle($request, Closure $next, ... $roles)
{
    if (!Auth::check()) 
        return redirect('login');

    $user = Auth::user();

    foreach($roles as $role) {
        if($user->hasRole($role))
            return $next($request);
    }
    return redirect('login');
}

Reference:

https://pakainfo.com/laravel-middleware-multiple-roles-parameters/

  • Hello @capaci, thanks for the answer but that’s not exactly what I asked. Maybe I wasn’t clear in my question. I would like to know how a route protected by authentication (login) can be accessed by users authenticated by different Guards. I’ll change my question and be more specific.

  • I ended up solving just creating another route using the same stretch and changing the Guards in each. Sorry to take your time with such a childish question.

  • Imagine, man. No question is childish. I don’t know the best way, but if you solved your problem, shoot ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.