Sometimes we need to restrict the amount of traffic for a given route or group of routes in Laravel. That means you want to accept a limited number of requests for a given route in Laravel. In this case, how can you solve this or how can you handle this situation in your Laravel application?

For solving this situation, Laravel throttle middleware comes. From the version of Laravel 8, we can do the same thing using Laravel Rate Limit facades.

Laravel Throttle Middleware

The Laravel 9 throttle middleware accepts two arguments that determine the maximum number of requests that can be made in a given number of minutes.

routes/web.php

<?php

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

 

Here 60 is the number of requests you can make per 1 minute. Hope you got the point.

What is Rate Limit in Laravel?

We can do the above things using the Laravel Rate Limiters. We can define our custom Rate Limiter in any Service Provider typically it is good to be in RouteServiceProvider like so. But your Laravel version must be a minimum of Laravel 8 before using Laravel Rate Limiters. 

app\Providers\RouteServiceProvider.php

<?php

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

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

 

Now we can define testing Rate Limiter using its name with throttle middleware like throttle:testing instead of throttle:60,1:

routes/web.php

<?php

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

 

Read also: Complete Explanation With Example On Laravel Middleware

 

Hope it can help you.