Applying Middleware to Routes
A middleware class only takes effect once it's actually attached to a route or group of routes. Laravel offers several ways to do this, depending on how broadly the middleware should apply.
Applying Middleware to a Single Route
The most direct approach is chaining the middleware() method onto an individual route definition, listing one or more middleware by their registered name or class.
Applying Middleware to a Group of Routes
When several routes need the same middleware, wrapping them in a Route::middleware([...])->group() call avoids repeating the same call on every single route.
| Approach | Example |
|---|---|
| Single route | Route::get('/dashboard', ...)->middleware('auth') |
| Grouped routes | Route::middleware(['auth'])->group(function () {...}) |
| Controller constructor | $this->middleware('auth') inside a controller |
Stacking Multiple Middleware
- Routes can chain more than one middleware, executed in the order listed
- Middleware defined in a group applies to every route nested inside it
- Named middleware makes route definitions far more readable than full class names
Some middleware should run on every single request, while others should only apply to a handful of routes — understanding that distinction is the focus of the next topic.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.
