How to Register a Laravel Middleware for Specific Request Logic (Laravel 11)
Register a Laravel middleware by creating a class with a handle() method, then add it to the $middleware array for global execution, the $middlewareAliases array for route-specific assignment, or the $middlewareGroups array for group-wide application in app/Http/Kernel.php.
Middleware in Laravel acts as a filter for HTTP requests, allowing you to inspect, modify, or reject incoming traffic before it reaches your application logic. In Laravel 11 and newer versions, the laravel/framework repository provides a flexible pipeline architecture managed by the HTTP Kernel and Router classes. This guide demonstrates how to properly register a Laravel middleware using the exact mechanisms defined in the framework source code.
Understanding Laravel's Middleware Architecture
The middleware system is coordinated between Illuminate\Foundation\Http\Kernel and Illuminate\Routing\Router. The Kernel maintains three primary collections in src/Illuminate/Foundation/Http/Kernel.php:
$middleware– Classes executed on every incoming request$middlewareAliases– Short names mapped to fully-qualified class names$middlewareGroups– Named stacks likewebandapi
When a request arrives, the Kernel builds a pipeline using these collections, and the Router resolves specific middleware for individual routes via resolveMiddleware() in src/Illuminate/Routing/Router.php.
Creating a Middleware Class
Before registration, you need a middleware class that implements the required interface.
The Handle Method Signature
A valid middleware must define a handle() method accepting an Illuminate\Http\Request object and a Closure representing the next layer in the pipeline. The method should return a response. For example, src/Illuminate/Http/Middleware/TrustProxies.php demonstrates this pattern.
Here is a practical implementation that logs request details:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class LogRequestData
{
public function handle(Request $request, Closure $next)
{
Log::info('Incoming request', [
'url' => $request->fullUrl(),
'method' => $request->method(),
'ip' => $request->ip(),
]);
return $next($request);
}
}
Methods to Register a Laravel Middleware
Laravel provides three primary registration patterns depending on your scope requirements. All configurations reside in your application's app/Http/Kernel.php, which extends the framework's base Kernel.
Register as Global Middleware
Global middleware runs on every HTTP request. Add your class to the $middleware property or use the pushMiddleware() method defined in src/Illuminate/Foundation/Http/Kernel.php (lines 56-66).
protected $middleware = [
// \App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\LogRequestData::class,
];
Register as Route Middleware Alias
For selective application, register an alias in $middlewareAliases. This maps a short string to your class, enabling usage in route definitions. The underlying mechanism calls Router::aliasMiddleware() in src/Illuminate/Routing/Router.php (lines 4345-4348).
protected $middlewareAliases = [
'log.request' => \App\Http\Middleware\LogRequestData::class,
];
Apply it to specific routes:
use Illuminate\Support\Facades\Route;
Route::get('/profile', function () {
// ...
})->middleware('log.request');
Register Within Middleware Groups
Middleware groups like web and api bundle multiple middleware under one name. Add your class to $middlewareGroups or use pushMiddlewareToGroup() from src/Illuminate/Routing/Router.php (lines 5112-5114).
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\App\Http\Middleware\LogRequestData::class,
],
];
Dynamic registration at runtime:
app('router')->pushMiddlewareToGroup('web', \App\Http\Middleware\LogRequestData::class);
Middleware Priority and Execution Order
Laravel sorts middleware using the $middlewarePriority array in src/Illuminate/Foundation/Http/Kernel.php (lines 101-115). This ensures critical middleware like authentication runs before others regardless of registration order.
You can modify priority using:
prependToMiddlewarePriority()– Add to the beginningappendToMiddlewarePriority()– Add to the end
The SortedMiddleware class handles the actual sorting logic during pipeline construction.
Summary
- Create a middleware class implementing
handle($request, Closure $next)inapp/Http/Middleware/ - Register globally by adding to
$middlewareinapp/Http/Kernel.phpor callingpushMiddleware() - Register as alias by mapping in
$middlewareAliasesto use with->middleware('alias')in routes - Register in groups by adding to
$middlewareGroupsor usingpushMiddlewareToGroup()for theweborapistacks - Control execution order via
$middlewarePriorityin the Kernel to ensure proper sequencing
Frequently Asked Questions
What is the difference between global and route middleware in Laravel?
Global middleware runs on every incoming HTTP request through the $middleware array in the Kernel, while route middleware (registered as aliases) only executes when explicitly attached to specific routes or controllers using the middleware() method. Global middleware is ideal for logging, CORS handling, or maintenance mode checks, whereas route middleware suits authentication or rate limiting for specific endpoints.
How do I apply middleware to a specific controller in Laravel 11?
You can apply middleware to a controller by calling the middleware() method within the controller's constructor. This method accepts either the alias string defined in $middlewareAliases or the fully-qualified class name. For example: $this->middleware('log.request'); or $this->middleware(\App\Http\Middleware\LogRequestData::class);. You can also specify which controller methods should use the middleware by chaining only() or except() methods.
Can I register middleware dynamically without modifying the Kernel file?
Yes, you can register middleware at runtime using the router instance. Use app('router')->pushMiddleware() for global middleware, app('router')->aliasMiddleware() for aliases, or app('router')->pushMiddlewareToGroup() for groups. These methods correspond to the underlying implementations in Illuminate\Routing\Router and allow package developers or service providers to register middleware without requiring manual edits to app/Http/Kernel.php.
Where does Laravel store the default middleware groups like 'web' and 'api'?
The default web and api middleware groups are defined in the $middlewareGroups property of your application's app/Http/Kernel.php, which extends Illuminate\Foundation\Http\Kernel. The framework's base Kernel does not pre-populate these groups; they are configured in the application skeleton. However, the framework provides the underlying group handling logic in src/Illuminate/Routing/Router.php through methods like pushMiddlewareToGroup() and middlewareGroup().
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →