In the Laravel framework, middleware plays a critical role in processing HTTP requests. It's commonly used for authentication, authorization, logging, request modifications, and more. Middleware offers an elegant and flexible way to intercept and handle requests, making application logic cleaner and more maintainable.
Middleware in Laravel is stored in the app/Http/Middleware directory and can be created using the Artisan CLI or manually. At its core, middleware is a class with a handle() method that accepts a request and a closure, allowing the request to either be passed along or halted with a response.
When a request hits the application, it passes through all registered middleware in the defined order. If any middleware returns a response, the processing stops, and the response is immediately sent back to the client.
There are two main types of middleware registration in Laravel: global and route-specific. Global middleware is defined in the $middleware property of app/Http/Kernel.php and is applied to every request:
protected $middleware = [
\App\Http\Middleware\CheckToken::class,
];
Route middleware is only applied to specific routes. It is registered in the $routeMiddleware property:
protected $routeMiddleware = [
'checkRole' => \App\Http\Middleware\CheckRole::class,
];
You can then use it like this in a route definition:
Route::get('/admin', function () {
// Admin page
})->middleware('checkRole');
The order in which middleware is registered determines the order of execution. Global middleware is executed in the array's order, while route middleware follows the sequence specified in route definitions. Use php artisan route:list to inspect middleware usage and order.
When several routes require the same middleware, you can group them together for cleaner code. Here's an example:
Route::group(['middleware' => 'admin'], function () {
// All admin routes
});
All routes within this group will automatically use the admin middleware.
Here’s a step-by-step example of creating and using a custom authentication middleware:
1. Create the middleware:
php artisan make:middleware Authenticate
2. Define its logic in app/Http/Middleware/Authenticate.php:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Authenticate
{
public function handle(Request $request, Closure $next)
{
$token = $request->header('Authorization');
if ($token != 'secret_token') {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request);
}
}
3. Register the middleware globally in Kernel.php:
protected $middleware = [
\App\Http\Middleware\Authenticate::class,
];
4. Apply it to a route:
Route::get('/api', function () {
// Protected API endpoint
})->middleware('auth');
This middleware checks the Authorization header and compares it with a predefined token. If the token is invalid, it returns a 401 Unauthorized error in JSON format. Otherwise, the request proceeds as normal.
Laravel middleware offers a powerful mechanism to intercept, modify, or block HTTP requests before they reach controllers or after they leave them. By mastering middleware usage, developers can create more secure, maintainable, and scalable applications. Proper use of middleware helps keep controller logic clean and the application architecture robust.