PHP › Routing & Middleware

How does a middleware pipeline execute multiple middleware in sequence, and how does the concept of calling the next middleware let each one decide whether to continue processing the request?

Intermediate

Answer

A middleware pipeline chains together multiple middleware functions, with each middleware receiving both the current request and a reference to the next piece of code in the chain, and by explicitly calling that next function, a middleware allows the request to continue on to the following middleware or eventually the actual route handler, while a middleware can also choose not to call next at all, effectively short circuiting the pipeline and immediately returning its own response, such as rejecting an unauthenticated request before it ever reaches the intended route.
function logMiddleware($request, $next) {
    error_log('Incoming request: ' . $request->path);
    $response = $next($request);
    error_log('Response sent');
    return $response;
}
Real-world example A logging middleware records details both before and after the actual route handler runs, by calling next in the middle of its own logic, demonstrating how a single middleware can wrap logic around the entire rest of the request handling pipeline.

Common follow-ups: What happens if a middleware forgets to call the next function at all?;In what order does a framework typically execute several middleware assigned to the same route?