Home > Software design >  Laravel how to add middleware to controller with multiple roles?
Laravel how to add middleware to controller with multiple roles?

Time:02-09

What I want to achieve is that the EventController's functions/ methods should be available for role:organizer, and only the view() method [URL: /events/{id}] from the same controller should also be available to role:artist.

I've tried to implement that by creating the following middleware to check for the logged-in user's role: class UserRole

{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return Application|JsonResponse|RedirectResponse|Redirector
     */
    public function handle(Request $request, Closure $next, ...$roles)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        if (!Auth::check()) {
            return redirect(RouteServiceProvider::HOME);
        }

        if (in_array(strtolower(Auth::user()->type), $roles)) {
            return $next($request);
        }

        return redirect('/login');
    }
}

Then in my EventController, I have assigned the following middlewares in the constructor:

public function __construct()
    {
        $this->middleware(['auth', 'verified', 'onboarding', 'role:organizer']);
        $this->middleware(['role:artist,organizer'])->only('view');
    }

When I run php artisan route:list - I get the list as I want it to be, only events/{id} has both the organizer and artist role enter image description here

However when I log in with user artist and try to access localhost/events/10 - I get redirected to the /login screen, but when I try to access the same URL with a role organizer it works..

Is there any suggestion on how to make it work? If there's something you don't understand let me know and I'll help you!

CodePudding user response:

The problem is that you have attached the middleware to view endpoint with 'role:organizer' twice in the first time it only check is user has role organizer and it doing redirect and it's not going check the second time so to exclude this behavior you should attache middlewares like this

$this->middleware(['auth', 'verified', 'onboarding']);
$this->middleware(['role:artist,organizer'])->only('view');
$this->middleware('role:organizer')->except('view');// because it already added above
  •  Tags:  
  • Related