In this lesson, we will explore how to create, configure, and apply middleware within your Laravel application. Middleware helps manage tasks such as authentication, logging, and request modifications. It's akin to security checks at an airport ensuring everything is in order before you board your flight.
Let's understand how the request-response cycle works in Laravel when middleware is involved:
- A request is made to your Laravel application.
- The request passes through the middleware stack first. Each middleware can perform tasks such as authentication, logging, or modifying the request.
- After passing through the middleware stack, the request reaches the application's core logic (controllers).
- The response generated by the application passes through the middleware stack again. Each middleware can perform tasks such as logging or modifying the response.
- The response is sent back to the client.
Middleware can be applied globally to all routes, to specific routes, or to specific groups of routes. This flexibility allows you to manage requests effectively and efficiently.
Here's a simple example of how middleware can be used to log the duration of each request:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class LogRequestTime
{
public function handle(Request $request, Closure $next)
{
$startTime = microtime(true);
$response = $next($request);
$endTime = microtime(true);
$duration = $endTime - $startTime;
Log::info('Request Time:', [
'method' => $request->method(),
'url' => $request->fullUrl(),
'duration' => $duration
]);
return $response;
}
}
Let's break down the code snippet above:
- We define a middleware class
LogRequestTime that implements the handle method. The handle method receives the incoming request and a closure that represents the next middleware in the stack or if there are no more middleware, the application's core logic.
- We calculate the start time of the request using
microtime(true).
- We pass the request to the next middleware in the stack or the application's core logic using
$next($request).
- We calculate the end time of the request using
microtime(true) and calculate the duration of the request by subtracting the start time from the end time.
- We log the request time information using Laravel's
Log facade.
- Finally, we return the response generated by the application.
This middleware logs the duration of each request, providing valuable information for performance monitoring and optimization.
We have successfully created a middleware that logs the duration of each request. However, to use this middleware, we need to register it in the application's middleware stack. To do this, we need to add the middleware to the $middleware property in the app/Http/Kernel.php file:
protected $middleware = [
// Other middleware...
\App\Http\Middleware\LogRequestTime::class
];
protected $routeMiddleware = [
// Other route middleware...
'log.request.time' => \App\Http\Middleware\LogRequestTime::class
];
In the $middleware property, we add the middleware to the global middleware stack, which means it will be applied to all requests. In the $routeMiddleware property, we add the middleware to the route middleware group, which allows us to apply the middleware to specific routes or route groups. In this case, we give the middleware an alias log.request.time.
As a final step, we can apply the middleware to a route or a group of routes in the routes/web.php file:
<?php
use App\Http\Controllers\TodoController;
Route::middleware(['log.request.time'])->group(function () {
Route::get('/todos', [TodoController::class, 'index']);
Route::get('/todos/{id}', [TodoController::class, 'show']);
Route::post('/todos', [TodoController::class, 'store']);
Route::put('/todos/{id}', [TodoController::class, 'update']);
Route::delete('/todos/{id}', [TodoController::class, 'destroy']);
});
Route::get('/some-other-route', function () {
return 'This route does not use the log.request.time middleware';
});
In this example, we apply the log.request.time middleware (remember we gave it an alias in the Kernel.php file) to a group of routes that handle CRUD operations for todos. This means that the LogRequestTime middleware will be executed for each request to these routes, logging the duration of each request. If you don't want to apply the middleware to a particular route, you can define the route outside the middleware group, as shown in the example above.
By following these steps, you can create, configure, and apply middleware in your Laravel application. Middleware is a powerful tool that allows you to manage requests effectively and efficiently, enhancing the security, performance, and reliability of your application.