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 () {
    //
});
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources