How to use rate limiting in Livewire components
2.xTo enable rate limiting in a Livewire component, apply the DanHarrin\LivewireRateLimiting\WithRateLimiting trait.
Once the trait is included, you can call $this->rateLimit() within your component methods to throttle execution. If the limit is exceeded, the package throws a TooManyRequestsException. It is recommended to catch this exception and convert it into a ValidationException to provide user-friendly feedback.
<?php
namespace App\Http\Livewire\Login;
use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use DanHarrin\LivewireRateLimiting\WithRateLimiting;
use Illuminate\Validation\ValidationException;
use Livewire\Component;
class Login extends Component
{
use WithRateLimiting;
public function submit()
{
try {
// Limit to 10 attempts every 60 seconds
$this->rateLimit(10);
} catch (TooManyRequestsException $exception) {
throw ValidationException::withMessages([
'email' => "Slow down! Please wait another {$exception->secondsUntilAvailable} seconds to log in.",
]);
}
// ... logic after successful rate limit check
}
}