Rate limiting is a crucial feature in web applications to control the number of requests a user can make to the server within a specific timeframe. This helps protect your application from abuse, such as brute force attacks and ensures fair usage of your resources. Read this if you need more information.
In this post, we'll dive deep into Laravel's rate-limiting capabilities and how to implement them in your application.
Using middleware
//routes/web/php
Route::get('/hello', function () {
return response()
->json([
'version' => '1.0.0',
'latest_update' => '2022-01-01',
'data' => 'Hello World!'
]);
})->middleware(['throttle:hello']);
Define Rate Limits in the AppServiceProvider.php
// app/providers/AppServiceProvider.php
/**
* Bootstrap any application services.
*/
public function boot(): void
{
RateLimiter::for('hello', function ($request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
How it works?
Manually Incrementing Attempts
Check it out from the Laravel 11 resource from here.
Route::get('/create-transcript', function (Request $request) {
if (RateLimiter::tooManyAttempts(
key: 'transcript:' . $request->ip(),
maxAttempts: 5
)) {
return 'Too many attempts';
}
echo 'Transcript created';
RateLimiter::increment('transcript:' . $request->ip(), amount: 5);
});