Rate Limiting in Laravel controls the number of requests a user or client can make to your application within a given timeframe. It is commonly used to prevent abuse, protect resources, and ensure fair usage of APIs.
Rate Limiting is built into Laravel's middleware system, leveraging the ThrottleRequests
middleware to enforce limits based on client identifiers like IP addresses or API keys.
Applying rate limiting to a route:
Route::middleware('throttle:60,1')->group(function () {
Route::get('/api/posts', [PostController::class, 'index']);
});
This limits the route to 60 requests per minute. You can also customize limits dynamically:
Route::middleware('throttle:custom')->group(function () {
Route::get('/api/posts', [PostController::class, 'index']);
});
In App\Providers\RouteServiceProvider
, define the custom rate limiter:
RateLimiter::for('custom', function (Request $request) {
return Limit::perMinute(100)->by($request->user()?->id ?: $request->ip());
});
This approach ensures flexibility and security while managing API traffic effectively.