dev3 ·
I want to stop brute force login attempts and limit my API to 60 requests per minute per user, with a stricter limit for a heavy export endpoint. How do I define and apply rate limiters in Laravel 12?
#laravel#security#rate-limiting
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
I want to stop brute force login attempts and limit my API to 60 requests per minute per user, with a stricter limit for a heavy export endpoint. How do I define and apply rate limiters in Laravel 12?
#laravel#security#rate-limiting
Define named limiters in AppServiceProvider::boot() using RateLimiter::for, then attach them with the throttle middleware.
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
RateLimiter::for('exports', function (Request $request) {
return [
Limit::perMinute(2)->by($request->user()->id),
Limit::perDay(20)->by($request->user()->id),
];
});
RateLimiter::for('login', function (Request $request) {
$key = strtolower($request->input('email')).'|'.$request->ip();
return Limit::perMinute(5)->by($key);
});
}
Apply on routes:
Route::middleware('throttle:login')->post('/login', LoginController::class);
Route::middleware(['auth:sanctum', 'throttle:exports'])->get('/export', ExportController::class);
For API routes the default group applies throttle:api once you enable it in bootstrap/app.php with $middleware->throttleApi().
Custom response
Limit::perMinute(5)->by($key)->response(fn () => response()->json(['message' => 'Slow down'], 429));
Pitfalls
array driver never limits across requests; use redis, database or file. For Redis there is $middleware->throttleWithRedis().Retry-After and X-RateLimit-Remaining headers.The DEV3 snippet on token rate limits shows this with Sanctum abilities.