I'm building an API on top of Laravel. I'd like to use the built in rate limiting capabilities by using the Throttle
middleware.
Problem is, when the throttle middleware triggers the response is:
// Response headers
Too Many Attempts.
My API uses an error payload in JSON that looks like the following:
// Response headers
{
"status": "error",
"error": {
"code": 404,
"message": "Resource not found."
}
}
What is the best way to get the Throttle
middleware to return an output in the manner I require?
Make your own shiny middleware, extend it by original, and override methods you like to be overriden.
$ php artisan make:middleware ThrottleRequests
Open up kernel.php and remove (comment out) original middleware and add yours.
ThrottleRequests.php
<?php
namespace App\Http\Middleware;
use Closure;
class ThrottleRequests extends \Illuminate\Routing\Middleware\ThrottleRequests
{
protected function buildResponse($key, $maxAttempts)
{
return parent::buildResponse($key, $maxAttempts); // TODO: Change the autogenerated stub
}
}
kernel.php
.
.
.
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
//'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
//'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'throttle' => \App\Http\Middleware\ThrottleRequests::class
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With