Starting with Laravel 11: Understanding Middleware

Middleware in Laravel 11 acts as a checkpoint for HTTP requests, allowing you to apply additional checks such as country restrictions, age verification, and gender-based access.

Middleware helps control access and modify requests before they reach the application logic.

Types of Middleware

Laravel provides three types of middleware:

  1. Global Middleware – Applies to all requests.
  2. Group Middleware – Applies to specific groups of routes.
  3. Route Middleware – Applies to individual routes.

1. Global Middleware

Global middleware is applied to every request in the application. To create one, use the following Artisan command: php artisan make:middleware CheckAge

Once created, register it in app/Http/Kernel.php under the $middleware array:

protected $middleware = [
    \App\Http\Middleware\CheckAge::class,
];

Inside the handle function of CheckAge middleware, you can define conditions and redirections:

public function handle($request, Closure $next)
{
    if ($request->age < 18) {
        return redirect('home');
    }
    return $next($request);
}

2. Group Middleware

Group middleware is used to apply a set of middleware to specific routes. To create a middleware group, first, create a new middleware using Artisan: php artisan make:middleware MenOnly

Register it in app/Http/Kernel.php inside the $middlewareGroups array:

protected $middlewareGroups = [
    'menonly' => [
        \App\Http\Middleware\MenOnly::class,
    ],
];

Define a route group in routes/web.php:

Route::group(['middleware' => 'menonly'], function () {
    Route::get('member', function () {
        return view('member');
    });
});

3. Route Middleware

Route middleware is applied to specific routes individually. It must first be registered in app/Http/Kernel.php inside the $routeMiddleware array:

protected $routeMiddleware = [
    'ccode' => \App\Http\Middleware\CountryCode::class,
];

Now, apply it to a route in routes/web.php:

Route::get('/users/{name}', [DummyController::class, 'loadView'])->middleware('ccode');

Understanding Middleware with a Highway Analogy

Think of routes/web.php as a highway toll plaza. Middleware acts as toll booths, enforcing different rules:

  • Global Middleware: A toll applied to all roads.
  • Group Middleware: A toll applied only to state highways.
  • Route Middleware: A toll applied only on a specific road.

Who manages all this? The Kernel (like an army colonel) determines which middleware is global, grouped, or routed, ensuring structured and efficient request handling.

Conclusion

Middleware in Laravel 11 provides a powerful way to filter HTTP requests and apply access control logic. By understanding the types of middleware and how they are applied, you can effectively manage route access and security in your Laravel application.