Interview frequency: …
Short answer
It passes the request through a chain of wrapped Closures; Terminable Middleware provides terminate($request, $response), which runs after the response has been sent to the client.
Explanation
Middlewares rely on Illuminate\Pipeline\Pipeline. Each middleware receives $request and a $next function; it can inspect the request before calling $next($request), or modify the response when the call returns. If the Middleware implements terminate(), Laravel calls it after the client has received the full response, making it suitable for logging and metrics collection without delaying the user.
Code example
class LogRequest {
public function handle($request, Closure $next) {
return $next($request);
}
public function terminate($request, $response): void {
// Runs after the response reaches the browser
Log::info("Request finished with code: " . $response->status());
}
}Common mistakes
- Running long operations inside handle() after $next() instead of using terminate().