Laravel: There is a RateLimiter and you didn’t know

You have a rate limit, and you have a rate limit, and you have a rate limit!

How it works?

The class is relatively simple, in part thanks to the InteractsWithTime trait that handles… well, interacting with time.

$limiter = app(RateLimiter::class);
/**
* Do something tied to rate limiting
*
* @param \Illuminate\Cache\RateLimiter $limiter
* @return \Illuminate\Http\Response
* @throws \Illuminate\Validation\ValidationException
*/
public function notTooManyTimes(RateLimiter $limiter)
{
if ($limiter->tooManyAttempts('my_action')) {
// .. do something
}
// ...
}
$limiter = app(RateLimiter::class, [
'cache' => Cache::store('memcache')
]);
/**
* Bootstrap any application services.
*
*
@return void
*/

public function boot()
{
// ...

$this->app
->when(\Illuminate\Cache\RateLimiter::class)
->needs(\Illuminate\Contracts\Cache\Repository::class)
->give(function ($app) {
return $app->make('cache')->store('memcached');
});

Basic usage

The basic flow of rate-limiting something is this:

  1. You use hit() each time you want subtract 1 to the attempts left, with the name to identify what rate limiter and the decay seconds of it.
  2. Optionally, reset the counter using resetAttempts(), or additionally reset the timer using clear().
  • retriesLeft(): The number of retries left.
  • available(): How much time must pass to retry.

Can we stop reckless Requests?

The RateLimiter is very basic. Most of the time you can stop the user using the throttle middleware, leaving our controller logic clean. But sometimes, we need to use the Request to effectively throttle an action, which you can’t do with the throttle middleware alone.

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.