0
0
LaravelHow-ToBeginner · 3 min read

How to Use Middleware Groups in Laravel: Syntax and Examples

In Laravel, middleware groups let you bundle multiple middleware under a single key in app/Http/Kernel.php. You apply the group to routes or route groups using the middleware method, simplifying middleware management.
📐

Syntax

Middleware groups are defined in the $middlewareGroups array inside app/Http/Kernel.php. Each group has a name and an array of middleware classes or aliases. You apply a group to routes using the middleware method with the group name.

  • Group definition: Name and list of middleware.
  • Route usage: Use middleware('groupName') on routes or route groups.
php
<?php
// In app/Http/Kernel.php
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // other middleware
    ],

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

// In routes/web.php
Route::middleware('web')->group(function () {
    Route::get('/', function () {
        return 'Home page with web middleware group';
    });
});
💻

Example

This example shows how to define a custom middleware group called admin and apply it to a route group. The admin group includes authentication and a custom middleware to check admin access.

php
<?php
// In app/Http/Kernel.php
protected $middlewareGroups = [
    'admin' => [
        'auth',
        \App\Http\Middleware\CheckAdmin::class,
    ],
];

// In routes/web.php
Route::middleware('admin')->group(function () {
    Route::get('/dashboard', function () {
        return 'Admin dashboard';
    });

    Route::get('/settings', function () {
        return 'Admin settings';n    });
});
Output
Visiting /dashboard or /settings requires authentication and admin check middleware to pass.
⚠️

Common Pitfalls

  • Forgetting to register middleware aliases in $routeMiddleware causes errors when using aliases in groups.
  • Applying middleware groups to routes that already have conflicting middleware can cause unexpected behavior.
  • Not using groups and instead repeating middleware on many routes leads to cluttered code.
php
<?php
// Wrong: Using alias not registered in $routeMiddleware
protected $middlewareGroups = [
    'custom' => [
        'nonexistentAlias', // This will cause an error
    ],
];

// Right: Register alias first
protected $routeMiddleware = [
    'check.admin' => \App\Http\Middleware\CheckAdmin::class,
];

protected $middlewareGroups = [
    'custom' => [
        'auth',
        'check.admin',
    ],
];
📊

Quick Reference

Use middleware groups to organize middleware for routes efficiently. Define groups in app/Http/Kernel.php under $middlewareGroups. Apply groups to routes with middleware('groupName'). Always register middleware aliases in $routeMiddleware before using them in groups.

Key Takeaways

Middleware groups bundle multiple middleware for easy reuse on routes.
Define groups in app/Http/Kernel.php under $middlewareGroups.
Apply groups to routes using middleware('groupName') method.
Register middleware aliases in $routeMiddleware before using in groups.
Using groups keeps route definitions clean and manageable.