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.
Registering a Short Name for Your Middleware
Before you can write ->middleware('role'), Laravel must know which class that name points to. Where you register it depends on the framework version.
// Laravel 11 and later: bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'role' => \App\Http\Middleware\EnsureUserHasRole::class,
]);
})
// Laravel 10 and earlier: app/Http/Kernel.php
protected $middlewareAliases = [
'role' => \App\Http\Middleware\EnsureUserHasRole::class,
];
You can also skip the alias and pass the class directly: ->middleware(EnsureUserHasRole::class).
Passing Parameters to Middleware
Many checks need extra information, such as which role is allowed. Add values after a colon, separated by commas, and receive them as extra arguments in handle().
Route::get('/reports', [ReportController::class, 'index'])
->middleware('auth', 'role:admin,manager');
// app/Http/Middleware/EnsureUserHasRole.php
public function handle(Request $request, Closure $next, string ...$roles)
{
if (! in_array($request->user()?->role, $roles, true)) {
abort(403);
}
return $next($request);
}
Here auth runs first and makes sure a user is logged in, then the role check runs. Listing them in this order matters, because the role check needs a user to inspect.
Each middleware either passes the request on by calling $next($request) or stops it by returning a response or aborting. Because every layer wraps the next, code written after $next() runs on the way back out, which is where you would add response headers or timing logs.
Controller Middleware in Newer Laravel
From Laravel 11, the base controller no longer provides $this->middleware() in the constructor. Instead, a controller implements HasMiddleware and returns its middleware from a static method, with optional only and except filters.
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
class InvoiceController extends Controller implements HasMiddleware
{
public static function middleware(): array
{
return [
'auth',
new Middleware('role:accountant', only: ['store', 'update']),
new Middleware('throttle:30,1', except: ['index']),
];
}
}
Excluding a Route From Group Middleware
Sometimes one route inside a protected group must stay open, such as a public status page. Use withoutMiddleware() on that route instead of moving it out of the group.
Route::middleware(['auth'])->group(function () {
Route::get('/account', [AccountController::class, 'show']);
Route::get('/status', StatusController::class)->withoutMiddleware('auth');
});
Note that withoutMiddleware removes only route middleware. Global middleware, which runs on every request, cannot be removed this way.
Checking and Debugging
- Run
php artisan route:list -vto see which middleware is attached to each route. - Use middleware groups such as
webandapifor cross-cutting needs like sessions, CSRF protection and throttling, and keep route-level middleware for specific checks. - If a route returns 403 or redirects to login unexpectedly, check whether a group higher up added the middleware.
- Keep middleware focused on one job; heavy business logic belongs in controllers or services.
- Write a feature test for each protected route that confirms guests and wrong roles are blocked.
- Prefer named routes and aliases over long class names to keep route files readable.
- Remember that route caching (
php artisan route:cache) stores middleware assignments too; clear or rebuild the cache after changing them on a server.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.