0
0
Laravelframework~5 mins

Middleware groups in Laravel

Choose your learning style9 modes available
Introduction

Middleware groups help you organize multiple middleware into one set. This makes it easy to apply many middleware at once to routes.

You want to apply authentication and logging middleware together to many routes.
You have a set of middleware for web pages and another set for API routes.
You want to keep your route files clean by grouping middleware logically.
You need to reuse the same middleware stack in different parts of your app.
Syntax
Laravel
protected $middlewareGroups = [
    'groupName' => [
        MiddlewareClass1::class,
        MiddlewareClass2::class,
        // more middleware
    ],
];
Middleware groups are defined in the app/Http/Kernel.php file.
You use the group name in your routes to apply all middleware in that group at once.
Examples
This example shows the default 'web' middleware group with cookie encryption, session start, and CSRF protection.
Laravel
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],
];
This example shows the 'api' group with rate limiting and route model binding middleware.
Laravel
protected $middlewareGroups = [
    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];
Sample Program

This example defines a middleware group named 'customGroup' with two middleware: CheckAge and LogAccess. Then it applies this group to a route. When visiting '/dashboard', both middleware run before showing the message.

Laravel
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;
use App\Http\Middleware\CheckAge;
use App\Http\Middleware\LogAccess;

class Kernel extends HttpKernel
{
    protected $middlewareGroups = [
        'customGroup' => [
            CheckAge::class,
            LogAccess::class,
        ],
    ];
}

// In routes/web.php

use Illuminate\Support\Facades\Route;

Route::middleware(['customGroup'])->group(function () {
    Route::get('/dashboard', function () {
        return 'Welcome to dashboard';
    });
});
OutputSuccess
Important Notes

Middleware groups simplify applying many middleware to routes.

You can add parameters to middleware inside groups like 'throttle:60,1'.

Always define middleware classes before adding them to groups.

Summary

Middleware groups bundle multiple middleware under one name.

They are defined in app/Http/Kernel.php inside the $middlewareGroups array.

Use the group name in routes to apply all middleware in that group easily.