Middleware in Laravel
β± Estimated reading time: 2 min
Middleware in Laravel act as a filter between an incoming HTTP request and the applicationβs response. They allow you to inspect, modify, or reject requests before they reach controllers, making them essential for tasks like authentication, authorization, logging, and request validation.
1. What Is Middleware?
Middleware are classes that handle HTTP requests before or after the controller is executed.
Request flow:
Common uses:
-
Authentication checks
-
Authorization
-
CSRF protection
-
Logging requests
-
Maintenance mode checks
2. Default Middleware in Laravel
Laravel includes built-in middleware such as:
-
authβ Ensures the user is authenticated -
guestβ Redirects authenticated users -
verifiedβ Email verification -
throttleβ Rate limiting -
csrfβ Prevents cross-site request forgery
These are registered automatically.
3. Creating Custom Middleware
Create middleware using Artisan:
File location:
4. Middleware Structure
Example middleware:
-
$requestβ Incoming request -
$next($request)β Pass request forward
5. Registering Middleware
Middleware are registered in app/Http/Kernel.php.
Route Middleware
6. Applying Middleware to Routes
Single Route
Route Group
7. Applying Middleware to Controllers
Apply middleware inside a controller:
Exclude methods:
8. Global Middleware
Global middleware run on every request.
Defined in Kernel.php:
9. Middleware Parameters
Middleware can accept parameters:
Middleware class:
10. Terminable Middleware
Middleware can run logic after the response:
Conclusion
Middleware in Laravel provide a powerful mechanism to control request flow and application security. By using built-in and custom middleware, developers can keep controllers clean, enforce rules consistently, and build secure, maintainable applications.
Register Now
Share this Post
β Back to Tutorials