In this tutorial, we will learn how to set ‘Route Rate Limit’ in Laravel 8, and 9.
Step 1 – Configure RouteServiceProvider
Open your app/Providers/RouteServiceProvider.php file.
Create a custom rate limit, as shown below.
The example below shoes, ‘global’ as a custom word. You can use any word of your choice.
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);
});
}
Another example as shown below helps control upload requests when specific users try to upload more than 100 times per minute or access the upload route. We can also add IP based restrictions, as shown below.
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
Next step after creating a custom rate limiter, is to attach it to our route as shown below.
Route::middleware(['throttle:uploads'])->group(function () {
Route::post('/media_upload', function () {
//
});
});
- throttle – the default routing middleware. You can see that it can be assigned by default in
kernel.php
- uploads – method is a custom rate limiter you had set up in the previous step.
Hope the tutorial helped you get the concept of Laravel Rate limiter. If you have any more doubts, Please feel free to ask us in the comments section.
Happy Coding!