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.
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
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.
Create middleware using Artisan:
File location:
Example middleware:
$request → Incoming request
$next($request) → Pass request forward
Middleware are registered in app/Http/Kernel.php.
Apply middleware inside a controller:
Exclude methods:
Global middleware run on every request.
Defined in Kernel.php:
Middleware can accept parameters:
Middleware class:
Middleware can run logic after the response:
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.
Take quizzes related to this topic and see where you stand!
Start Quiz Now