0
0
Laravelframework~30 mins

Terminable middleware in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
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 LogRequestTime
Add a property startTime to store the request start time
Implement the handle method to set startTime and pass the request to the next middleware
Implement the terminate method to calculate and log the total time taken
Register 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
1
Create the middleware class with a startTime property
Create a middleware class named LogRequestTime in the app/Http/Middleware directory. Add a public property called startTime to store the request start time.
Laravel
Need a hint?

Define a class with a public property named startTime.

2
Add the handle method to set startTime and pass the request
Inside the LogRequestTime class, add a public method handle that accepts $request and Closure $next. Set $this->startTime to the current time using microtime(true). Then return $next($request).
Laravel
Need a hint?

The handle method runs before the request is processed. Use microtime(true) to get the current time.

3
Add the terminate method to log the total time taken
Add a public method terminate to the LogRequestTime class that accepts $request and $response. Calculate the total time by subtracting $this->startTime from the current time using microtime(true). Use Laravel's logger() helper to log the message: 'Request took ' . $totalTime . ' seconds.'.
Laravel
Need a hint?

The terminate method runs after the response is sent. Use it to log the total time.

4
Register the LogRequestTime middleware in app/Http/Kernel.php
Open app/Http/Kernel.php. Add \App\Http\Middleware\LogRequestTime::class to the $middleware array to register it as global middleware.
Laravel
Need a hint?

Register the middleware globally by adding it to the $middleware array in the Kernel class.