What are Laravel Middlewares and how do they work?

What are Laravel Middlewares and how do they work?

What are Laravel Middlewares and how do they work?

Question

What are Laravel Middlewares and how do they work?

Answer

Middleware acts as a series of layers around the HTTP request/response cycle. Each middleware can inspect the request, modify it, pass it to the next layer, or terminate it early (e.g. redirect unauthenticated users).

Creating Middleware

php artisan make:middleware EnsureUserIsActive
// app/Http/Middleware/EnsureUserIsActive.php
class EnsureUserIsActive
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->user()?->is_active) {
            return redirect('/suspended');
        }

        return $next($request); // pass to the next middleware / controller
    }
}

Registering Middleware

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'active' => EnsureUserIsActive::class,
    ]);
})

Applying to Routes

Route::get('/dashboard', [DashboardController::class, 'index'])
    ->middleware(['auth', 'active']);

Types of Middleware

  • Global — runs on every request
  • Route — applied to specific routes or groups
  • Terminable — runs after the response is sent
All Comments