Middleware in Laravel

What is Middleware in Laravel?

Middleware in Laravel works as a filter for HTTP requests that enter your application. It enables you to analyze, modify, and reject requests before they reach your routes or controllers.


Origin

Middleware is a basic idea in Laravel, inspired by comparable patterns in other frameworks, and provides a flexible manner of handling request lifecycle logic.


Why is Middleware Used?

  1. Enhanced Security: Used for authentication, authorization, and input validation.
  2. Promotes Modular Design: Encapsulates reusable logic in different levels.
  3. Streamlines Requests: Addresses cross-cutting issues such as logging and caching efficiently.

Best Practices.

  1. Organize Middleware: Organize middleware logically to reduce redundancy.
  2. Use Middleware Groups: Combine numerous middleware into a single group for common activities.
  3. Avoid Heavy Logic: Use lightweight middleware to retain 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');

This middleware determines the age of the user in the incoming request and moves users under 18 to the home page.

Read more