Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel rate limit to return a JSON payload

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?

like image 574
Cody Smith Avatar asked Dec 10 '22 14:12

Cody Smith


1 Answers

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
];
like image 116
Kyslik Avatar answered Jan 03 '23 00:01

Kyslik