Skip to content

Laravel rate limit API routes with throttle middleware

PHP Dasun Kalupahana 110 views

<?php

// routes/api.php: 60 requests per minute
Route::middleware('throttle:60,1')->group(function () {
    Route::get('/posts', [PostController::class, 'index']);
});

// Custom limiter in AppServiceProvider::boot()
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('login', function (Request $request) {
    return Limit::perMinute(5)->by($request->ip());
});

// Apply it
Route::post('/login', LoginController::class)->middleware('throttle:login');

Limits how many requests a client can make per minute and returns a 429 when exceeded. Use it on login, API and public endpoints to stop abuse.

Learn more on the blog

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.