Here, we are going to see how to set up route rate limit Laravel 8 and 9,
Step 1 – Configure RouteServiceProvider
app/Providers/RouteServiceProvider.php
Example 1 – Custom rate limit (global is a custom word, you can do it with your custom name)
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('global', function (Request $request) {
return Limit::perMinute(1000);
});
}
Example 2 – Here’s another example where we can control upload requests when certain users try to upload more than 100 times per minute/access the upload route, and we have IP based restrictions too.
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('uploads', function (Request $request) {
return $request->user()
? Limit::perMinute(100)->by($request->user()->id)
: Limit::perMinute(10)->by($request->ip());
});}
Step 2 – Use Rate Limiters to Routes
After creating a custom rate limiter, we have to attach this to our route as below,
Route::middleware(['throttle:uploads'])->group(function () {
Route::post('/media_upload', function () {
//
});
});
- throttle is the default routing middleware. You can see that it is assigned by default in kernel.php
- uploads method is a custom rate limiter which has been set up in #step 1.
I hope this has helped you to get a basic understanding of Laravel Rate Limiter. If you still have any doubts, feel free to ask me in the comment section.
Cheers!