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
Battle Ready Laravel

The ultimate guide to auditing, testing, fixing and improving your Laravel applications so you can build better apps faster and with more confidence.

Visit Battle Ready Laravel
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 $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Laravel Forge logo

Laravel Forge

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

Laravel Forge
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
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
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
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Confidently Extract Single Array Items with Laravel's Arr::sole() Method image

Confidently Extract Single Array Items with Laravel's Arr::sole() Method

Read article
Safely Retry API calls in Laravel image

Safely Retry API calls in Laravel

Read article
Laravel's AsHtmlString Cast for Elegant HTML Attribute Management image

Laravel's AsHtmlString Cast for Elegant HTML Attribute Management

Read article
NativePHP for Mobile v1 — Launching May 2 image

NativePHP for Mobile v1 — Launching May 2

Read article
Map Eloquent Attributes into an Object Using the Collection Cast in Laravel 12.10 image

Map Eloquent Attributes into an Object Using the Collection Cast in Laravel 12.10

Read article
Converting Array Values to Enum Instances with Laravel's mapInto Method image

Converting Array Values to Enum Instances with Laravel's mapInto Method

Read article