What is middleware
Middleware is a mechanism for inspecting and filtering HTTP requests entering your application. You can slot in processing before and after the request is handed off to a controller. For example, Laravel includes authentication middleware. If the user is not authenticated, it redirects them to the login screen; if they are authenticated, it lets the request continue into the application. Beyond authentication, you can create middleware for many purposes, such as logging, CSRF protection, and rate limiting. For details on Laravel 13’s CSRF protection, see CSRF protection.User-defined middleware is typically placed in the
app/Http/Middleware directory.Built-in middleware
Laravel provides two middleware groups by default:web and api.
The web group is automatically applied to routes/web.php, and the api group is applied to routes/api.php.
Aliases are also configured for commonly used middleware so you can refer to them by short names.
Creating middleware
Create a new middleware with themake:middleware Artisan command.
app/Http/Middleware/EnsureTokenIsValid.php.
Write your request-handling logic in the handle method.
$next($request) passes the request to the next step in the application.
When the condition isn’t met, return a redirect or response to stop the request.
Before and after processing
Middleware can perform work before or after the request.Registering middleware
Global middleware
To run middleware on every request, add it to the global stack viawithMiddleware in bootstrap/app.php.
append adds to the end of the stack. Use prepend to add to the beginning.
Assigning middleware to routes
To apply middleware to specific routes, call themiddleware method on the route definition.
withoutMiddleware.
Middleware aliases
You can define short aliases for long class names. Configure them inbootstrap/app.php.
Middleware groups
Grouping multiple middleware under a single key makes it easier to apply them to routes. UseappendToGroup or prependToGroup in bootstrap/app.php.
web or api group, dedicated methods are available.
Middleware parameters
Middleware can accept additional parameters. Add them after the$next argument in the handle method.
:.
Example: an authentication check middleware
A simple example that redirects users who aren’t logged in.Next steps
HTTP requests
Learn how to receive request data in your controllers.