In Laravel applications, middleware acts as a powerful intermediary between incoming HTTP requests and your application's core logic. It empowers you to execute specific actions before a request reaches its intended route, enabling tasks like authentication, authorization, request manipulation, and response formatting. This tutorial delves into the process of creating and employing custom middleware in Laravel 11, equipping you to enhance your application's security, flexibility, and maintainability.
Crafting Custom Middleware in Laravel 11: A Practical Guide
1. Generating the Middleware Class:
Leverage Laravel's Artisan command to streamline the creation process:
php artisan make:middleware EnsureTokenIsValid
This command generates a new class named EnsureTokenIsValid.php
within the app/Http/Middleware
directory. This class serves as the foundation for your custom middleware's functionality.
2. Implementing the Middleware Logic:
Open the newly created EnsureTokenIsValid.php
class and define the handle
method, which forms the core of your middleware's behavior.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class EnsureTokenIsValid
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request) $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$token = $request->header('X-API-Token'); // Replace with your token retrieval method
if (!$token || $token !== config('app.api_token')) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request);
}
}
- In this example, the
handle
method retrieves the API token from the request header and compares it to the value stored in your application's configuration (config('app.api_token')
). - If the token matches, the request proceeds to the intended route (
$next($request)
). Otherwise, an unauthorized response (401 status code) is returned.
3. Registering the Middleware
-
To make your custom middleware operational, incorporate it into Laravel's middleware stack. There are two primary approaches:
- Global Middleware: Applicable to all incoming requests.
- Route-Specific Middleware: Applies only to designated routes or route groups.
3.a) Global Middleware Registration:
- Navigate to the
app/Http/Kernel.php
file. - Within the
$middleware
property, append your middleware class:
protected $middleware = [
// ... other middleware
App\Http\Middleware\EnsureTokenIsValid::class,
];
3.b) Route-Specific Middleware Registration:
- Using Route Closures:
Route::get('/protected-route', function () { // Route logic })->middleware('ensureTokenIsValid');
- Using Route Group with Middleware:
Route::group(['middleware' => 'ensureTokenIsValid'], function () { Route::get('/protected-route-1', function () { // Route logic }); Route::get('/protected-route-2', function () { // Route logic }); });