Understanding Laravel Middleware: Running Processes Before and After Requests
Laravel middleware provides a convenient mechanism for filtering HTTP requests entering your application. Middleware acts as a bridge between a request and a response, allowing you to execute code before and after the request is handled by your application.
According to the Laravel Middleware documentation, middleware can perform various tasks such as authentication, CORS, logging, and more.
How Middleware Works
Middleware in Laravel follows a layered approach:
- Before Request: Middleware can inspect, modify, or reject requests before they reach your controllers
- After Request: Middleware can modify responses before they're sent back to the client
- Request Pipeline: Multiple middleware can be stacked, creating a pipeline that processes requests sequentially
Common Use Cases
In my projects, I've used middleware extensively for:
- Authentication: Verifying user sessions and API tokens before allowing access to protected routes
- Rate Limiting: Preventing abuse by limiting the number of requests from a single IP or user
- Request Validation: Validating and sanitizing input data before it reaches controllers
- Logging: Tracking API usage, request times, and errors for monitoring and debugging
- CORS Handling: Managing cross-origin resource sharing for API endpoints
- Localization: Setting application locale based on user preferences or headers
Creating Custom Middleware
Laravel makes it easy to create custom middleware. For example, I created middleware to log API requests and measure response times:
public function handle(Request $request, Closure $next)
{
$startTime = microtime(true);
// Code executed BEFORE the request
$response = $next($request);
// Code executed AFTER the request
$duration = microtime(true) - $startTime;
Log::info('API Request', [
'url' => $request->fullUrl(),
'method' => $request->method(),
'duration' => $duration
]);
return $response;
}
Middleware Groups
Laravel provides convenient middleware groups:
- web: For web routes (sessions, CSRF protection, cookie encryption)
- api: For API routes (throttling, stateless authentication)
- Custom Groups: You can define your own middleware groups for specific route sets
Terminable Middleware
Sometimes you need to perform actions after the HTTP response has been sent to the browser. Laravel supports terminable middleware for this purpose:
public function terminate($request, $response)
{
// This code runs after the response is sent
// Useful for logging, cleanup, or background tasks
}
Best Practices
When working with middleware:
- Keep middleware focused on a single responsibility
- Use middleware for cross-cutting concerns (authentication, logging, etc.)
- Avoid heavy processing in middleware - use queues for intensive tasks
- Test middleware thoroughly as it affects all routes it's applied to
- Consider middleware priority when multiple middleware need to run in a specific order
Real-World Example
In the UNIXIA platform, I implemented middleware to:
- Authenticate API requests using tokens before processing
- Log all API interactions for audit purposes
- Apply rate limiting to prevent API abuse
- Set up CORS headers for cross-origin requests
This middleware layer ensures that all requests are properly authenticated, logged, and rate-limited before reaching the application logic, providing security and observability.
Middleware is a powerful feature that helps keep your controllers clean and focused on business logic, while handling cross-cutting concerns in a reusable way.
For detailed information, refer to the official Laravel Middleware documentation.