Laravel Middleware Tutorial (Registering Middleware)
In the previous tutorial, we learned how to define middleware. Now, let’s see how to register middleware and assign it to routes.
Global Middleware
Sometimes, you want a middleware to run on every HTTP request (e.g., security checks, request validation).
To do this, register it in bootstrap/app.php:
use App\Http\Middleware\EnsureTokenIsValid;
->withMiddleware(function (Middleware $middleware) {
$middleware->append(EnsureTokenIsValid::class);
});
append()→ adds middleware to the end of the global stack.prepend()→ adds middleware to the beginning.
This means all routes will pass through this middleware automatically.
Manually Managing Laravel’s Default Global Middleware
By default, Laravel has its own global middleware stack (e.g., handling CORS, trimming strings).
You can override it like this:
->withMiddleware(function (Middleware $middleware) {
$middleware->use([
\Illuminate\Foundation\Http\Middleware\InvokeDeferredCallbacks::class,
// \Illuminate\Http\Middleware\TrustHosts::class,
\Illuminate\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Http\Middleware\ValidatePostSize::class,
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
]);
});
Here, you replace Laravel’s default stack with your own configuration.
Assigning Middleware to Routes
Instead of applying middleware globally, you can attach it to specific routes.
use App\Http\Middleware\EnsureTokenIsValid;
Route::get('/profile', function () {
return "Profile page";
})->middleware(EnsureTokenIsValid::class);
Multiple Middleware on a Route
Route::get('/', function () {
return "Homepage";
})->middleware([First::class, Second::class]);
Excluding Middleware
Sometimes, you assign middleware to a group but want to exclude it for certain routes.
Example 1 – Exclude from one route:
Route::middleware([EnsureTokenIsValid::class])->group(function () {
Route::get('/', fn() => "Home");
Route::get('/profile', fn() => "Profile")
->withoutMiddleware([EnsureTokenIsValid::class]);
});
Example 2 – Exclude from the whole group:
Route::withoutMiddleware([EnsureTokenIsValid::class])->group(function () {
Route::get('/profile', fn() => "Profile");
});
Note: withoutMiddleware() only works with route middleware, not global middleware.
Middleware Groups
Middleware groups let you combine multiple middleware under one key.
use App\Http\Middleware\First;
use App\Http\Middleware\Second;
->withMiddleware(function (Middleware $middleware) {
$middleware->appendToGroup('group-name', [
First::class,
Second::class,
]);
$middleware->prependToGroup('group-name', [
First::class,
Second::class,
]);
});
Using Groups on Routes
Route::get('/', fn() => "Home")->middleware('group-name');
Route::middleware(['group-name'])->group(function () {
Route::get('/dashboard', fn() => "Dashboard");
});
Laravel’s Default Middleware Groups
Laravel provides two built-in groups:
web group
- Encrypt cookies
- Manage sessions
- CSRF protection
- Route binding
api group
- Route binding
- Throttle API requests
Laravel automatically applies:
web→ to routes inroutes/web.phpapi→ to routes inroutes/api.php
You can append/prepend to these groups:
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
EnsureUserIsSubscribed::class,
]);
$middleware->api(prepend: [
EnsureTokenIsValid::class,
]);
});
Middleware Aliases
Aliases give middleware a short name instead of using the full class name.
use App\Http\Middleware\EnsureUserIsSubscribed;
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'subscribed' => EnsureUserIsSubscribed::class,
]);
});
Now you can use:
Route::get('/profile', fn() => "Profile")->middleware('subscribed');
Laravel already provides default aliases like:
auth→Illuminate\Auth\Middleware\Authenticateguest→Illuminate\Auth\Middleware\RedirectIfAuthenticatedthrottle→Illuminate\Routing\Middleware\ThrottleRequests
Sorting Middleware (Priority)
Sometimes, the order of execution matters.
You can define the priority:
->withMiddleware(function (Middleware $middleware) {
$middleware->priority([
\Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
\Illuminate\Cookie\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
]);
});
Important
- Global Middleware → runs on every request.
- Route Middleware → applies only to specific routes.
- Excluding Middleware → remove middleware from certain routes.
- Groups → combine multiple middleware under one key.
- Aliases → short names for middleware.
- Priority → control execution order.
Use global middleware for app-wide rules, route middleware for specific conditions, and groups for organization.
