Home > Net >  Laravel 9 multiple middleware in route
Laravel 9 multiple middleware in route

Time:01-15

I have this route, that should work for both middlewares

Route::middleware(['company', 'consultant'])->group(function () {
    Route::resource('/tasks', TaskController::class);
});

If I do

Route::middleware(['consultant'])->group(function () {
    Route::resource('/tasks', TaskController::class);
});

Or

Route::middleware(['company'])->group(function () {
    Route::resource('/tasks', TaskController::class);
});

Both work, yet the first example with both it does work just for the company.

In routeMiddleware I have as expected

'consultant' => \App\Http\Middleware\IsConsultant::class,
'company' => \App\Http\Middleware\IsCompany::class,

And in the Middleware folder

class IsCompany
{
    public function handle(Request $request, Closure $next)
    {
        if (Auth::user() &&  Auth::user()->type == 2) {
             return $next($request);
        }

        return redirect('dashboard')->with('error','You have not admin access');
    }
}

class IsConsultant
{
    public function handle(Request $request, Closure $next)
    {
        if (Auth::user() &&  Auth::user()->type == 1) {
             return $next($request);
        }

        return redirect('dashboard')->with('error','You have not admin access');
    }
}

CodePudding user response:

If you want both of the middleware to succeed and pass the request, they won't. They are mutually exclusive, since one needs Auth::user()->type == 2 and other Auth::user()->type == 1

If one succeeds, the other has to fail by definition.

You can rather have a single middleware with in_array(Auth::user()->type, [1, 2], true) that'd work when the user type is either 1 or 2, if that's what you're looking for.

  • Related