Outsource Laravel Development Partner - $3200/Month | Bacancy

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
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Tinkerwell logo

Tinkerwell

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

Tinkerwell
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
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
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
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 →
The Laravel Community Mobile App Helps You Discover Events and Connect With Developers image

The Laravel Community Mobile App Helps You Discover Events and Connect With Developers

Read article
A PHP Package for Concurrent Website Crawling image

A PHP Package for Concurrent Website Crawling

Read article
A Clean API for Reading PHP Attributes image

A Clean API for Reading PHP Attributes

Read article
Serve Markdown Versions of Your Laravel Pages to AI Agents image

Serve Markdown Versions of Your Laravel Pages to AI Agents

Read article
The Inertia v3 Beta is Here image

The Inertia v3 Beta is Here

Read article
Polyscope Is an Ai-First Dev Environment for Orchestrating Agents image

Polyscope Is an Ai-First Dev Environment for Orchestrating Agents

Read article