PHP › Routing & Middleware

What is middleware in the context of a web application, and how does it let you run logic before or after a request is handled by its intended route?

Beginner

Answer

Middleware is a piece of code that sits within the request handling pipeline, running either before a request reaches its intended route handler, after the handler produces a response, or both, letting you implement cross cutting concerns, such as authentication checks, logging, or modifying request and response data, in a reusable way that can be applied consistently across many different routes without duplicating that same logic within every individual route handler.
function authMiddleware($request, $next) {
    if (!$request->user) {
        return redirect('/login');
    }
    return $next($request);
}
Real-world example An application applies an authentication middleware to every route within its admin panel, ensuring the exact same login check runs consistently before any admin route is ever reached, without needing to repeat that check inside every single admin controller method.

Common follow-ups: What is the difference between global middleware and route specific middleware?;How does middleware relate to the concept of the request response lifecycle?