How to implement Rate Limiting in Laravel
Limiting the number of requests per minute sent to an application is often necessary to protect against attacks trying to saturate your server or to brute force authentication forms. That’s why Laravel comes with a rate limiting mechanism, which we will learn to use here.
There are two ways to implement rate limiting with Laravel:
- Using the Rate Limiter Middleware: to rate limiting incoming HTTP requests before reaching the controller
- Using the Rate Limiting abstraction: to interact more finely with the rate limiter at the controller level
Get started
The throttle middleware is made to protect routes against excessive reception of too many HTTP requests and restricting them once a limit has been reached.
To get started, you should start by defining the rate limiter configurations that your application needs. For that, go to the App\Providers\RouteServiceProvider class in the definition of the configureRateLimiting() method.
| <?php | |||||||||||||||||||||||||||||||||||||
| namespace App\Providers; | |||||||||||||||||||||||||||||||||||||
| use Illuminate\Cache\RateLimiting\Limit; | |||||||||||||||||||||||||||||||||||||
| use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; | |||||||||||||||||||||||||||||||||||||
| use Illuminate\Support\Facades\RateLimiter; | |||||||||||||||||||||||||||||||||||||
| class RouteServiceProvider extends ServiceProvider | |||||||||||||||||||||||||||||||||||||
| { | |||||||||||||||||||||||||||||||||||||
| // ... | |||||||||||||||||||||||||||||||||||||
| public function boot(): void | |||||||||||||||||||||||||||||||||||||
| { | |||||||||||||||||||||||||||||||||||||
| $this->configureRateLimiting(); | |||||||||||||||||||||||||||||||||||||
| // ... | |||||||||||||||||||||||||||||||||||||
| } | |||||||||||||||||||||||||||||||||||||
| /** | |||||||||||||||||||||||||||||||||||||
| * Configure the rate limiters for the application. | |||||||||||||||||||||||||||||||||||||
| */ | |||||||||||||||||||||||||||||||||||||
| protected function configureRateLimiting(): void | |||||||||||||||||||||||||||||||||||||
| { | |||||||||||||||||||||||||||||||||||||
| RateLimiter::for('global', function (Request $request) { | |||||||||||||||||||||||||||||||||||||
| return Limit::perMinute(1000); | |||||||||||||||||||||||||||||||||||||
| }); | |||||||||||||||||||||||||||||||||||||
| } | |||||||||||||||||||||||||||||||||||||
| }
In the above example, we have defined a rate limiter called You can create as many configurations as you want, with the names you want. We could for example imagine having Once you defined your rate limiters, you can apply them to routes you want to rate limite using the
|
No comments