To create and use middleware in Laravel for request and response handling, follow these steps:
Step 1: Create middleware Create a new middleware class using the artisan command:
php artisan make:middleware MyMiddleware
This will create a new middleware class named MyMiddleware in the app/Http/Middleware directory.
Step 2: Implement handle method Open the MyMiddleware class and implement the handle method. This method will be called for every incoming HTTP request. You can perform any request processing or modification in this method.
public function handle($request, Closure $next)
{
// Perform any request processing or modification
$response = $next($request);
// Perform any response processing or modification
return $response;
}
Step 3: Register middleware
Middleware can be registered globally or for specific routes. To register it globally, open the app/Http/Kernel.php file and add the MyMiddleware class to the $middleware
array. To register it for specific routes, add it to the $routeMiddleware
array.
protected $middleware = [
// ...
\App\Http\Middleware\MyMiddleware::class,
];
protected $routeMiddleware = [
// ...
'mymiddleware' => \App\Http\Middleware\MyMiddleware::class,
];
Note: The 'mymiddleware' is the alias used to reference the middleware in route definitions.
Step 4: Use middleware in routes To use the middleware in a route, add the middleware alias to the route definition either in the web.php or api.php file.
Route::get('/example', function () {
// ...
})->middleware('mymiddleware');
That's it! The middleware will now be applied to the route and the handle method will be called for each incoming request before further processing. You can add as many middleware classes as needed and stack them on a route for sequential processing.