DEV Community

Ali A. Dhillon
Ali A. Dhillon

Posted on

New simple way of creating custom Rate Limiters in Laravel 8

In Laravel we use throttle middleware to restrict the amount of traffic for a given route or group of routes. The throttle middleware accepts two parameters that determine the maximum number of requests that can be made in a given number of minutes.
For example:

Route::middleware('throttle:60,1')->get('/user', function () {
        //
});
Enter fullscreen mode Exit fullscreen mode

Here 60 is number of requests you can make in 1 minute.

Now in Laravel 8 there is a new way to create custom Rate Limiters.
We can define our custom Rate Limiter in any Service Provider typically it should be in RouteServiceProvider like so.

Rate limiters are defined using the RateLimiter facade's for method. The for method accepts a rate limiter name and a Closure that returns the limit configuration that should apply to routes that are assigned this rate limiter:

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('testing', function (Request $request) {
    return Limit::perMinute(1000);
});
Enter fullscreen mode Exit fullscreen mode

Now we can attach testing Rate Limiter using it's name with throttle middleware like throttle:testing instead of throttle:60,1:

Route::middleware('throttle:testing')->get('/user', function(){
    //
});
Enter fullscreen mode Exit fullscreen mode

For further reading check out the Laravel 8 Docs Rate Limiting.

Top comments (0)