Global middleware runs on every request to your Laravel app. It helps you add common checks or actions for all users.
0
0
Global middleware in Laravel
Introduction
You want to check if the user is authenticated on every page.
You need to log every request made to your app.
You want to set a security header for all responses.
You want to handle CORS (Cross-Origin Resource Sharing) for all requests.
You want to trim all input data from forms automatically.
Syntax
Laravel
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];This code goes inside the app/Http/Kernel.php file.
Each middleware class listed here runs on every HTTP request.
Examples
This example shows adding two middleware globally: one to trust proxies and one to check maintenance mode.
Laravel
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
];This example trims all input strings and converts empty strings to null for every request.
Laravel
protected $middleware = [
\App\Http\Middleware\TrimStrings::class,
\App\Http\Middleware\ConvertEmptyStringsToNull::class,
];Sample Program
This middleware adds a custom header to every HTTP response. Adding it to the global middleware list makes it run on all requests.
Laravel
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class AddCustomHeader { public function handle(Request $request, Closure $next) { $response = $next($request); $response->headers->set('X-Custom-Header', 'HelloWorld'); return $response; } } // Then in app/Http/Kernel.php add: // protected $middleware = [ // \App\Http\Middleware\AddCustomHeader::class, // // other middleware... // ];
OutputSuccess
Important Notes
Global middleware affects every request, so keep them efficient to avoid slowing your app.
You can still use route middleware for specific routes if you want to run middleware only sometimes.
Remember to register your custom middleware class in app/Http/Kernel.php under the $middleware array.
Summary
Global middleware runs on every request to your Laravel app.
It is defined in the $middleware array inside app/Http/Kernel.php.
Use it for tasks like authentication checks, logging, or modifying all responses.