niko craft
niko craft

Reputation: 2977

Throttling Requests in Laravel using Graham Campbell’s Laravel Throttle

I am using https://github.com/GrahamCampbell/Laravel-Throttle and I would like to return to the user a message of how many minutes they have to wait before they can try again. I've checked this tutorial: http://bicknoyle.com/blog/2015/10/09/throttling-requests-in-laravel/ and it provides following example:

public function render($request, Exception $e)
{
    if ($e instanceof \Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException) {
        return response('Too many requests. Slow your roll!');
    }
    return parent::render($request, $e);
}

How can I let user know how many minutes they have to wait?

I've tried dd($e); and it returns

-statusCode: 429
  -headers: array:1 [▼
    "Retry-After" => 120
  ]
  #message: "Rate limit exceeded."

but each time I refresh the page Retry-After stays at 120, it does not count down. Got any ideas how I could solve this?

Upvotes: 1

Views: 662

Answers (1)

ybom
ybom

Reputation: 21

If you're using Laravel 5.2 or above, the only thing you should do is to add this to your route:

'middleware' => 'throttle:5,10'

like this:

Route::group(['prefix' => 'api', 'middleware' => 'throttle:5,10'], function () {
    Route::get('people', function () {
        return Person::all();
    });
});

That will add the time left to make requests again, look this article:

https://mattstauffer.co/blog/api-rate-limiting-in-laravel-5-2

Upvotes: 2

Related Questions