In Laravel, rate limiting is used to restrict the number of requests a user can make to your application in a given time frame. This is commonly used for APIs to prevent abuse. Laravel provides a very elegant way to handle this using middleware and the RateLimiter facade. Here’s a detailed explanation:
1. Using the throttle Middleware (Simplest Way)
Laravel comes with a built-in throttle middleware that you can attach to your routes.
Example:
Route::middleware('throttle:10,1')->group(function () {
Route::get('/api/data', [ApiController::class, 'index']);
});
Explanation:
10→ Maximum 10 requests1→ Time window in minutes- So, the user can make 10 requests per 1 minute.
2. Custom Rate Limiting Using RateLimiter Facade
Laravel 8+ allows defining custom rate limiters in App\Providers\RouteServiceProvider.
Step 1: Open RouteServiceProvider.php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
Step 2: Define a custom limiter in the boot() method:
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
});
}
protected function configureRateLimiting()
{
RateLimiter::for('global', function ($request) {
return Limit::perMinute(60)->by($request->ip());
});
RateLimiter::for('login', function ($request) {
return Limit::perMinute(5)->by($request->input('email'));
});
}
Explanation:
Limit::perMinute(60)→ 60 requests per minute.by($request->ip())→ Rate limiting per IP address.- You can also use a user identifier for authenticated users (
$request->user()->id).
Step 3: Apply custom limiter to a route:
Route::middleware('throttle:login')->post('/login', [AuthController::class, 'login']);
3. Handling Too Many Requests
If a user exceeds the limit, Laravel automatically returns a 429 HTTP status code with a message:
{
"message": "Too Many Attempts."
}
You can customize this by catching the ThrottleRequestsException in your App\Exceptions\Handler.
4. Advanced Options
You can define more complex limits:
- Dynamic limits: Based on user type or role
- Different time windows:
perSecond(),perHour(),perDay() - Multiple keys: Track multiple identifiers simultaneously
Example:
RateLimiter::for('uploads', function ($request) {
return Limit::perHour(100)
->by($request->user()->id ?: $request->ip())
->response(function () {
return response()->json(['error' => 'Upload limit reached'], 429);
});
});
Which Laravel feature handles rate limiting?
RateLimiter facade and middleware like throttle.What is the default rate limiting middleware in Laravel?
throttle middleware is used. Example:Route::middleware('throttle:60,1')->group(function () { // Routes here });Where is rate limiting defined in Laravel?
App\Providers\RouteServiceProvider, inside the configureRateLimiting() method.What are different ways to identify users in rate limiting?
By IP address (for guests)
By custom keys (like API token)
How do you apply different rate limits for different routes?
Route::middleware('throttle:api')->get('/user', function () { return auth()->user(); });What happens when the rate limit is exceeded in Laravel?
Retry-AfterX-RateLimit-LimitX-RateLimit-RemainingHow to reset or clear rate limiting in Laravel?
php artisan cache:clearWhich storage does Laravel use for rate limiting?
Can you implement sliding window rate limiting in Laravel?
RateLimiter with custom logic or use Redis-based solutions.What is the difference between Limit::perMinute() and Limit::perHour()?
perMinute() allows X requests per minute.perHour() allows X requests per hour.Example:
Limit::perMinute(60); Limit::perHour(1000);✅ Summary
- Use
throttlemiddleware for simple limits. - Use
RateLimiterfacade for custom or dynamic limits. - Automatically returns
429 Too Many Requests. - Can be applied to IP, user, email, or any identifier.
