Installation:
composer require f1uder/livewire-throttling
Publish the config (if needed) with:
php artisan vendor:publish --provider="Nrox\LivewireThrottling\LivewireThrottlingServiceProvider"
First Use Case:
Add the ThrottlingTrait to a Livewire component and apply rate limiting to a method:
use Nrox\LivewireThrottling\ThrottlingTrait;
class MyComponent extends Component {
use ThrottlingTrait;
public function submitForm() {
$this->rateLimit('10'); // 10 requests per minute
// Rest of the logic...
}
}
Key Files to Review:
config/livewire-throttling.php (for customization)resources/lang/en/json (default error messages)app/Http/Livewire/ (your components)Basic Rate Limiting:
public function action() {
$this->rateLimit('5'); // 5 requests per minute
// Protected logic
}
Custom Callback Handling:
public function sensitiveAction() {
$this->rateLimit('3', function ($seconds) {
$this->dispatch('throttled', seconds: $seconds);
});
}
Dynamic Rate Limits:
public function dynamicAction() {
$limit = auth()->user()->throttle_limit ?? '10';
$this->rateLimit($limit);
}
Clearing Limits:
public function resetThrottle() {
$this->clearRateLimit();
}
user.throttle_limit) and pass dynamically.// app/Http/Middleware/ThrottleLivewire.php
public function handle($request, Closure $next) {
if ($request->wireable) {
$request->wire('component')->rateLimit('5');
}
return $next($request);
}
lang/{locale}/json.Session Dependency:
session() is available (e.g., avoid API-only setups).session()->put() explicitly if needed.Cache Invalidation:
clearRateLimit()) only affects the current session. For shared limits (e.g., IP-based), extend the trait or use Redis.Error Handling:
abort(429). Override with custom callbacks or middleware to log/throttle gracefully.Rate Limit Format:
X/Y syntax for custom intervals (e.g., rateLimit('5/10s') for 5 requests per 10 seconds). Default is per minute.session()->get('livewire_throttling') to debug stored limits.Log::debug('Throttle check:', ['key' => $this->getThrottleKey()]) in the trait for visibility.Custom Keys:
Override getThrottleKey() to use user-specific or IP-based keys:
protected function getThrottleKey() {
return 'user_' . auth()->id() . '_' . $this->methodName();
}
Storage Backend:
Replace the session storage with Redis by binding a custom ThrottleStore:
$this->app->bind(ThrottleStore::class, function () {
return new RedisThrottleStore();
});
Event Listeners:
Dispatch events for throttling (e.g., Throttled, ThrottleCleared) by extending the trait:
event(new Throttled($this, $seconds));
config/livewire-throttling.php (default_limit). Overrides per-method limits if not specified.'m'). Use 's' (seconds), 'h' (hours), or custom strings (e.g., '10s').How can I help you explore Laravel packages today?