How does Laravel's middleware system let you filter and process HTTP requests before they reach your application's route handlers, and how do you create custom middleware?
Short answer
Middleware provides a mechanism for filtering and processing HTTP requests as they pass through your application, letting you perform tasks such as verifying a user is authenticated, logging request details, or modifying the request or response, before that request ever reaches…
Advertisement
AModel answer
Middleware provides a mechanism for filtering and processing HTTP requests as they pass through your application, letting you perform tasks such as verifying a user is authenticated, logging request details, or modifying the request or response, before that request ever reaches its intended route handler, and Laravel makes it straightforward to create custom middleware classes and apply them selectively to specific routes or globally across the entire application.
class EnsureUserIsAdmin {
public function handle($request, Closure $next) {
if (!$request->user()->isAdmin()) {
abort(403);
}
return $next($request);
}
}Real-world example
An admin panel applies a custom middleware to all of its routes that automatically verifies the currently authenticated user has administrator privileges, rejecting the request immediately with a forbidden response before it ever reaches the actual admin controller logic.
Likely follow-ups
- In what order does Laravel execute multiple middleware assigned to the same route?
- What is the difference between global middleware and route specific middleware?
Related topics