To define a route with a specific middleware that runs only on failure in Laravel, you can follow these steps:
app/Http/Kernel.php
file and locate the $routeMiddleware
property at the top of the class. Add a new key-value pair for your custom middleware. For example:protected $routeMiddleware = [
// Other middleware definitions...
'custom.middleware' => \App\Http\Middleware\CustomMiddleware::class,
];
php artisan make:middleware CustomMiddleware
This will generate a new file called CustomMiddleware.php
inside the app/Http/Middleware
directory.
app/Http/Middleware/CustomMiddleware.php
file and modify the handle()
method. Since you only want the middleware to run on failure, you can use the response()
helper function to return a custom response when the request fails. For example:public function handle($request, Closure $next)
{
$response = $next($request);
// Check if the response has a 4xx or 5xx HTTP status code
if ($response->isClientError() || $response->isServerError()) {
// Do something on failure
return response()->json(['message' => 'Request failed'], $response->status());
}
return $response;
}
You can modify the logic inside the if
block to perform any specific actions you want when the request fails.
routes/web.php
or routes/api.php
file and define the route where you want to apply the middleware. To apply the middleware only on failure, you can use the middleware()
method on the route and provide the middleware name as an argument. For example:Route::get('/example', function () {
// Your route logic
})->middleware('custom.middleware');
With this setup, the CustomMiddleware
will only run if the request fails (returns a 4xx or 5xx HTTP status code).
Remember to replace 'custom.middleware'
with an appropriate name for your middleware and modify the logic in the CustomMiddleware
class according to your requirements.