Create a Terminable Middleware in Laravel
📖 Scenario: You are building a Laravel web application that needs to log the time taken to handle each HTTP request. You want to create middleware that runs both before and after the response is sent to the browser.
🎯 Goal: Build a terminable middleware in Laravel that logs the request start time before the request is handled and logs the total time taken after the response is sent.
📋 What You'll Learn
Create a middleware class named
LogRequestTimeAdd a property
startTime to store the request start timeImplement the
handle method to set startTime and pass the request to the next middlewareImplement the
terminate method to calculate and log the total time takenRegister the middleware in
app/Http/Kernel.php under the $middleware array💡 Why This Matters
🌍 Real World
Logging request times helps monitor application performance and identify slow requests in real web applications.
💼 Career
Understanding terminable middleware is important for Laravel developers to run code after responses, useful for logging, cleanup, and analytics.
Progress0 / 4 steps