Laravel Rate Limiting a Custom Route

Laravel Rate Limiting a Custom Route

Laravel Rate Limiting a Custom Route

Define the limiter in AppServiceProvider then attach it to any route.

// app/Providers/AppServiceProvider.php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

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

// routes/web.php
Route::post('/contact/send', [ContactController::class, 'send'])
    ->middleware(['throttle:contact'])
    ->name('contact.send');

When the limit is exceeded Laravel automatically returns a 429 Too Many Requests response.

All Comments