How to assign multiple middlewares to a single route in Laravel

widget

In some cases, you’ll need to bunch multiple middlewares under a single key to send the assignment to a simple route. You can do this by utilizing the $middlewareGroups property of your HTTP kernel. Laravel comes with web and api middleware groups that contain common middleware you’ll need to apply to your web and API routes. Keep in mind that these middleware bunches are naturally connected by your application’s AppProvidersRouteServiceProvider to route inside your web and API route records:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

Middleware groups may be allocated to routes and controller activities with the same syntax as a single middleware. Middleware groups make it more helpful to allot numerous middleware to a route at once.

Route::get('/', function () {
    //
})->middleware('web');

Route::middleware(['web'])->group(function () {
    //
});