Global Middleware in Laravel: What It Is and How It Works
global middleware is code that runs on every HTTP request your application receives. It acts like a filter that processes all requests before they reach your routes or controllers, allowing you to handle tasks like security, logging, or input modification globally.How It Works
Think of global middleware as a security guard at the entrance of a building who checks every visitor before they enter. In Laravel, this guard is a piece of code that runs on every HTTP request, no matter which page or API endpoint the user wants to access.
This middleware can check things like if the user is logged in, if the request data is safe, or if the site is in maintenance mode. It runs automatically for all requests, so you don't have to add it manually to each route.
Laravel manages global middleware by listing them in the app/Http/Kernel.php file under the $middleware array. When a request comes in, Laravel runs each middleware in this list in order, then sends the request to the right controller or route.
Example
This example shows how to register a global middleware that logs every request's URL.
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; class LogRequestUrl { public function handle(Request $request, Closure $next) { Log::info('Request URL: ' . $request->fullUrl()); return $next($request); } } // Then, in app/Http/Kernel.php, add this middleware to the $middleware array: protected $middleware = [ // Other global middleware... \App\Http\Middleware\LogRequestUrl::class, ];
When to Use
Use global middleware when you want to apply a rule or action to every request in your Laravel app. For example:
- Checking if the site is in maintenance mode
- Logging all incoming requests for debugging
- Automatically trimming input data
- Setting security headers on every response
Global middleware is perfect for tasks that should never be skipped, no matter which page or API is accessed.
Key Points
- Global middleware runs on every HTTP request automatically.
- It is registered in the
$middlewarearray inapp/Http/Kernel.php. - It is useful for tasks like security, logging, and input processing.
- Global middleware ensures consistent behavior across your entire app.