Middleware

What is Middleware?

Middleware in Laravel acts as a filter for HTTP requests entering your application. It allows you to inspect, modify, or reject requests before they reach your routes or controllers.


Origin

Middleware has been a core concept in Laravel, inspired by similar patterns in other frameworks, to provide a flexible way of handling request lifecycle logic.


Why is it important?

  1. Improves Security: Used for authentication, authorization, and input validation.
  2. Encourages Modular Design: Encapsulates reusable logic into separate layers.
  3. Streamlines Requests: Applies cross-cutting concerns like logging or caching efficiently.

Best Practices

  1. Organize Middleware: Group middleware logically to reduce redundancy.
  2. Use Middleware Groups: Apply multiple middleware as a single group for common tasks.
  3. Avoid Heavy Logic: Keep middleware lightweight to maintain performance.

Example in Action

Create custom middleware:

php artisan make:middleware CheckAge

In the middleware class:

namespace App\Http\Middleware;

use Closure;

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

        return $next($request);
    }
}

Register the middleware in app/Http/Kernel.php:

protected $routeMiddleware = [
    'check.age' => \App\Http\Middleware\CheckAge::class,
];

Apply middleware to routes:

Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('check.age');

Middleware provides a powerful way to handle requests and enhance application functionality.