Laravel Fact — Group middleware

Middleware is great for pre- and post- processing for incoming HTTP requests, but assigning many same middlewares to many routes is a bit cumbersome. No worry, Laravel works it out for you! As routes can be grouped, same thing can be done to middleware.

You can do that by adding a new group and assigning any related middleware, that should be put into the group, into $middlewareGroups array property in app/Http/Kernel.php file. For example,

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

'api' => [
'throttle:60,1',
'auth:api',
],
];

To assign middleware group to related routes, use the middleware key on route definition,

Route::group(['middleware' => ['web']], function () {
// route definition
});

Note: this feature is for Laravel 5.2 and above.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.