Rate Limiting

    Laravel includes a simple to use rate limiting abstraction which, in conjunction with your application’s , provides an easy way to limit any action during a specified window of time.

    Typically, the rate limiter utilizes your default application cache as defined by the key within your application’s cache configuration file. However, you may specify which cache driver the rate limiter should use by defining a limiter key within your application’s cache configuration file:

    Basic Usage

    The Illuminate\Support\Facades\RateLimiter facade may be used to interact with the rate limiter. The simplest method offered by the rate limiter is the attempt method, which rate limits a given callback for a given number of seconds.

    The attempt method returns false when the callback has no remaining attempts available; otherwise, the attempt method will return the callback’s result or true. The first argument accepted by the attempt method is a rate limiter “key”, which may be any string of your choosing that represents the action being rate limited:

    1. use Illuminate\Support\Facades\RateLimiter;
    2. $executed = RateLimiter::attempt(
    3. 'send-message:'.$user->id,
    4. function() {
    5. }
    6. );
    7. if (! $executed) {
    8. return 'Too many messages sent!';
    9. }

    If you would like to manually interact with the rate limiter, a variety of other methods are available. For example, you may invoke the tooManyAttempts method to determine if a given rate limiter key has exceeded its maximum number of allowed attempts per minute:

    1. use Illuminate\Support\Facades\RateLimiter;
    2. if (RateLimiter::remaining('send-message:'.$user->id, $perMinute = 5)) {
    3. RateLimiter::hit('send-message:'.$user->id);
    4. // Send message...
    5. }

    Determining Limiter Availability

    When a key has no more attempts left, the method returns the number of seconds remaining until more attempts will be available:

    You may reset the number of attempts for a given rate limiter key using the clear method. For example, you may reset the number of attempts when a given message is read by the receiver:

    1. use Illuminate\Support\Facades\RateLimiter;
    2. /**
    3. * Mark the message as read.
    4. *
    5. * @param \App\Models\Message $message
    6. * @return \App\Models\Message
    7. */
    8. public function read(Message $message)
    9. {
    10. $message->markAsRead();
    11. RateLimiter::clear('send-message:'.$message->user_id);