Tinkerwell - The PHP Scratchpad

Configuring Middleware in Laravel

Published on by

Configuring Middleware in Laravel image

Starting in Laravel 11, the configuration of the middleware changed from using the HTTP Kernel to the application's bootstrap file. Though some existing applications upgraded from Laravel 10 to Laravel 11 and 12 might have middleware defined, a new Laravel application doesn't ship with an app/Http/Middleware folder:

Laravel 11 introduces a new default application structure with fewer default files. Namely, new Laravel applications contain fewer service providers, middleware, and configuration files.

However, we do not recommend that Laravel 10 applications upgrading to Laravel 11 attempt to migrate their application structure, as Laravel 11 has been carefully tuned to also support the Laravel 10 application structure.

So don't be thrown off if your application contains the default Laravel middleware. It's possible that the application upgraded to the latest version but kept the generated application middleware in the app structure.

Configuring Middleware in Laravel 11+

All of Laravel's middleware configuration now happens in the bootstrap/app.php file using the withMiddleware() method. From this file you can define global middleware, append, prepend, alias, etc.

If you're coming from Laravel 10 applications, you use the app/Http/Kernel.php file to configure routes using class properties. For global middleware, you use the $middleware property:

protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

As of Laravel 11 the Kernel class isn't part of the application code. Here's an example of defining a global middleware:

// bootstrap/app.php
 
use App\Http\Middleware\LogRequest;
 
->withMiddleware(function (Middleware $middleware) {
// Append to the end of the middleware stack
$middleware->append(LogRequest::class);
})

If you would like to add global middleware to the beginning of the stack, you can use the prepend method:

use App\Http\Middleware\LogRequest;
 
->withMiddleware(function (Middleware $middleware) {
// Add middleware to the beginning of the middleware stack
$middleware->prepend(LogRequest::class);
})

Defining Middleware Groups

In Laravel 10 or earlier, you define a middleware group using the Kernel's middleware groups property in the app/Http/Kernel.php file:

protected $middlewareGroups = [
'web' => [
// ...
],
'api' => [
// ...
],
'group-1' => [
// ...
],
];

In new Laravel applications, you can use the prepend/append to group methods:

$middleware->prependToGroup('group-1', First::class);
 
$middleware->appendToGroup('group-1', [
First::class,
Second::class,
);

You might also wonder: "How do I customize one of the built-in groups like web or API?" You can do so with the respective web and api methods:

$middleware->web(append: [
ExampleWebMiddleware::class,
]);
 
$middleware->api(prepend: [
ExampleApiMiddleware::class,
]);
 
$middleware->api(remove: [
ExampleApiMiddleware::class,
]);

Sorting Middleware

In Laravel 10 middleware priority was defined with a $middlewarePriority property in the HTTP Kernel.php file:

protected $middlewarePriority = [
\Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
\Illuminate\Cookie\Middleware\EncryptCookies::class,
// ...
];

As you might have guessed by now, you can configure priority using the bootstrap app.php file using the priority method:

->withMiddleware(function (Middleware $middleware) {
$middleware->priority([
//
]);

Middleware Aliases

In Laravel 10, you use the Kernel's $middlewareAliases property to map an alias string name to a middleware so you can conveniently add middleware to routes and groups:

protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
// ...
];

Starting in Laravel 11, you use the alias method:

->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'log' => LogRequest::class
]);
});
 
// In a route you can use `log`
Route::get('/messages/{message}', function () {
// ...
})->middleware('log');

Learn More

You can learn all about defining, configuring, and using middleware in the latest Laravel docs. You can check out the latest Middleware docs for Laravel 12, but be sure to use the appropriate documentation based on your Laravel version.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Bacancy

Outsource a dedicated Laravel developer for $3,200/month. With over a decade of experience in Laravel development, we deliver fast, high-quality, and cost-effective solutions at affordable rates.

Visit Bacancy
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Laravel 12.44 Adds HTTP Client afterResponse() Callbacks image

Laravel 12.44 Adds HTTP Client afterResponse() Callbacks

Read article
Handle Nested Data Structures in PHP with the Data Block Package image

Handle Nested Data Structures in PHP with the Data Block Package

Read article
Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup image

Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup

Read article
Seamless PropelAuth Integration in Laravel with Earhart image

Seamless PropelAuth Integration in Laravel with Earhart

Read article
Laravel API Route image

Laravel API Route

Read article
Laravel News 2025 Recap image

Laravel News 2025 Recap

Read article