Terminable Middleware
Terminable middleware runs AFTER the response has been sent to the browser. This is useful for tasks that shouldn't slow down the response — logging, analytics, cleanup operations. Define a terminate() method alongside the handle() method.
Terminable Middleware
class CollectAnalytics
{
public function handle(Request $request, Closure $next)
{
return $next($request); // Don't slow down the request
}
// Runs AFTER response is sent to browser
public function terminate(Request $request, Response $response): void
{
// Log analytics without slowing down the response
Analytics::track([
'url' => $request->fullUrl(),
'method' => $request->method(),
'status' => $response->getStatusCode(),
'duration' => microtime(true) - LARAVEL_START,
'user_id' => $request->user()?->id,
'ip' => $request->ip(),
]);
}
}
// The terminate() method is called by the HTTP kernel
// after the response is already sent to the client.
// The user's browser has already received the response
// while our analytics code runs in the background.Tip
Tip
Practice Terminable Middleware in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Each middleware calls next() to pass control or sends a response
Practice Task
Note
Practice Task — (1) Write a working example of Terminable Middleware from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Terminable Middleware is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.