Global vs. Route-Specific Middleware
Not every piece of middleware belongs everywhere. Laravel distinguishes between middleware that should run on literally every request and middleware that only makes sense for specific routes, and it provides clear registration points for each.
Global Middleware
Global middleware runs on every single HTTP request that reaches the application, regardless of which route it matches. This is the right place for concerns that genuinely apply everywhere, like trimming whitespace from input or handling maintenance mode.
Route Middleware
Route-specific middleware, sometimes called "route middleware," is registered with a short alias and only runs when explicitly attached to a route or group. This keeps the middleware pipeline lean, since routes that don't need a check, like a public homepage, don't pay its cost.
| Type | Runs On | Example |
|---|---|---|
| Global middleware | Every request, on every route | Trimming input, handling CORS |
| Route middleware | Only routes it's explicitly attached to | Authentication, role checks |
| Middleware groups | Predefined bundles, like "web" or "api" | Session, CSRF, cookie encryption |
Choosing the Right Scope
- Ask whether the logic genuinely applies to every request before making it global
- Prefer route-specific middleware for anything tied to a particular feature
- Use middleware groups to bundle related middleware that's often applied together
Authentication is one of the clearest examples of route-specific middleware in action, and it's worth a closer look on its own.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.
