Supports: Laravel 11, 12 & 13+ • PHP 8.2+ • Redis • Memcached • Database
Laravel Cooldown is a driver-based cooldown management package for Laravel that helps you enforce time-based restrictions on actions, workflows, and endpoints.
Manage cooldowns using cache or database storage, attach them directly to Eloquent models, protect routes with middleware, and extend the package with custom storage drivers—all through a clean, expressive API.
Unlike Laravel's built-in
RateLimiter, Laravel Cooldown is designed for persistent, entity-scoped action cooldowns and workflow delays with interchangeable cache and database storage.
// Option 1: High-level atomic execution (enforces + locks + sets cooldown on success)
Cooldown::for('send_otp', $user)->block(function () use ($otpService, $user) {
$otpService->send($user->phone);
}, duration: 120);
// Option 2: Step-by-step enforcement
Cooldown::for('password_reset', $user)->enforce();
// Do work...
Cooldown::for('password_reset', $user)->for(300);Laravel Cooldown is ideal for:
- Password reset requests
- Email verification
- SMS / OTP sending
- AI prompt generation
- Report exports
- Payment retries
- Promotional rewards
- API actions
- Spam protection
- User workflows
- Multiple Storage Drivers (Cache & Database): Switch seamlessly between high-performance
cachestores (Redis, Memcached, Array) and persistentdatabasestorage with automatic cleanup. - Expressive Fluent API: Chain expressive calls like
Cooldown::for('send_email', $user)->using('database')->for(300)or enforce limits withenforce(). - Atomic In-Flight Locking: Prevent concurrent double-clicks and race conditions using
block()or the built-in middleware. - Native Eloquent Integration: Attach the
HasCooldownstrait to any model for scoped action tracking ($user->cooldown('password_reset')->active()). - Route Middleware: Protect endpoints automatically using
cooldown:action_name,duration_in_secondswith automatic HTTP429enforcement andRetry-Afterheaders. - Immutable DTOs: Work safely with strict
CooldownInfoData Transfer Objects returning precision durations (remainingSeconds(),remainingForHumans()). - Prunable Database Storage: Built-in
Prunabletrait integration ensures expired database records never clutter your database. - Custom Driver Extensibility: Register custom storage drivers on the fly with closure-based creators via
Cooldown::extend().
While Laravel includes a built-in RateLimiter designed primarily for request throttling (e.g., "60 requests per minute"), Laravel Cooldown is engineered for temporal action constraints, workflow delays, and entity-scoped cooldowns across multiple storage backends.
| Feature | Laravel RateLimiter | Custom Cache Checks | Laravel Cooldown |
|---|---|---|---|
Fluent Builder API (Cooldown::for()->until()) |
❌ | ❌ | ✅ Expressive & Clean |
First-Class Eloquent Integration ($user->cooldown()) |
❌ | ❌ | ✅ Native (HasCooldowns) |
Driver-Based Architecture (cache & database) |
❌ Cache Only | ❌ Manual | ✅ Both Supported |
Atomic In-Flight Locking (block()) |
❌ | ✅ Built-in | |
| Success-Only Middleware Triggering | ❌ (Triggers on 4xx/5xx) | ❌ | ✅ Only on 2xx / 3xx |
| Temporal / Time-Based Delays & Constraints | ❌ Manual | ✅ Subsecond Precision | |
Immutable DTOs (CooldownInfo) |
❌ | ❌ | ✅ Strict (CarbonImmutable) |
Automatic Database Pruning (model:prune) |
N/A | ❌ Manual SQL | ✅ Built-in (Prunable) |
| Polymorphic Target Scoping (Models, Scalars, IPs) | ❌ Manual Keys | ❌ Manual Keys | ✅ Automatic Key Mapping |
Custom Driver Extensibility (Cooldown::extend()) |
❌ | ❌ | ✅ Closure / Container |
Event Dispatching (CooldownInitiated / Reset) |
❌ | ❌ | ✅ Configurable Events |
Ready to get started? Install the package with Composer:
composer require zaber-dev/laravel-cooldownPublish the configuration and database migrations:
php artisan vendor:publish --provider="ZaberDev\Cooldown\CooldownServiceProvider"Run migrations if you intend to use the database driver:
php artisan migrateThe configuration file config/cooldowns.php allows you to define your default storage driver, driver parameters, and event dispatching behaviors:
return [
/*
|--------------------------------------------------------------------------
| Default Cooldown Driver
|--------------------------------------------------------------------------
|
| Supported drivers: "cache", "database"
|
*/
'default' => env('COOLDOWN_DRIVER', 'cache'),
'drivers' => [
'cache' => [
'driver' => 'cache',
'store' => env('COOLDOWN_CACHE_STORE', null),
'prefix' => 'cooldowns:',
],
'database' => [
'driver' => 'database',
'table' => 'cooldowns',
],
],
'events' => [
'dispatch' => true,
],
];The Cooldown facade provides an expressive builder interface for setting, checking, enforcing, and resetting cooldowns.
use ZaberDev\Cooldown\Facades\Cooldown;
// Put a 5-minute cooldown on "export_reports" globally
Cooldown::for('export_reports')->for(300);
// Put a 1-hour cooldown on a specific user
Cooldown::for('send_sms', $user)->for(3600);
// Set expiration using Carbon / DateTimeInterface
Cooldown::for('daily_bonus', $user)->until(now()->endOfDay());// Check if an action is currently active (on cooldown)
if (Cooldown::for('send_sms', $user)->active()) {
$info = Cooldown::for('send_sms', $user)->info();
echo "Please wait " . $info->remainingForHumans() . " before trying again.";
echo "Seconds remaining: " . $info->remainingSeconds();
}
// Check if NOT on cooldown
if (Cooldown::for('send_sms', $user)->expired()) {
// Proceed with action...
}If you want to automatically halt execution and throw an HTTP 429 Too Many Requests exception when a cooldown is active or currently locked mid-execution, call enforce():
// Throws CooldownActiveException (HTTP 429) if active or mid-flight, automatically attaching 'Retry-After' header
Cooldown::for('login_attempt', $user)->enforce();For operations vulnerable to concurrent double-click bursts (e.g., sending SMS or OTPs), use the block() helper. block() acquires a temporary atomic lock while the callback executes and only starts the cooldown if execution completes successfully:
Cooldown::for('send_otp', $user)->block(function () use ($otpService, $user) {
$otpService->send($user->phone);
}, duration: 120);We strongly recommend using
block()for most use cases unless your workflow requires fine-grained manual locking across multi-step or asynchronous execution paths.
if (! Cooldown::for('process_payment', $order)->acquireLock(10)) {
throw new \Exception('Payment processing is already mid-flight.');
}
try {
// Perform payment charge...
} finally {
Cooldown::for('process_payment', $order)->releaseLock();
}// Immediately clear the cooldown for this action/target
Cooldown::for('send_sms', $user)->reset();Add the HasCooldowns trait to any Eloquent model to scope cooldowns directly to that entity:
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use ZaberDev\Cooldown\HasCooldowns;
class User extends Authenticatable
{
use HasCooldowns;
}You can now interact directly with your model instance:
$user = User::find(1);
// Set a 2-minute cooldown on "update_profile" for this user
$user->cooldown('update_profile')->for(120);
// Check active status
if ($user->cooldown('update_profile')->active()) {
return response()->json([
'message' => 'Too many profile updates.'
], 429);
}
// Enforce limits and throw 429 exception if active
$user->cooldown('update_profile')->enforce();
// Reset the cooldown
$user->cooldown('update_profile')->reset();When using the database driver, HasCooldowns also exposes a cooldowns() polymorphic relationship, allowing direct querying and bulk management:
// Get all database cooldown records assigned to this user
$activeCooldowns = $user->cooldowns()->where('expires_at', '>', now())->get();
// Delete all cooldown records for this user
$user->cooldowns()->delete();Protect routes declaratively without writing boilerplate checks in your controllers using the CheckCooldown middleware:
use Illuminate\Support\Facades\Route;
// Enforce a 60-second cooldown on form submissions per User / IP address
Route::post('/contact/submit', [ContactController::class, 'submit'])
->middleware('cooldown:contact_submit,60');
// Use a specific driver or dynamic action key
Route::post('/api/reports/generate', [ReportController::class, 'generate'])
->middleware('cooldown:report_gen,300,database');How the Middleware Works:
- Before executing your controller,
CheckCooldownverifies active status and acquires a temporary atomic in-flight lock across your configured driver to block concurrent double-click bursts (HTTP 429). - When your controller completes successfully (
2xxor3xx), the permanent temporal cooldown is initiated (for()). If the controller fails due to validation (4xx) or server errors (5xx), the temporary lock is released without applying a cooldown so the user can immediately correct their input and retry.
For an architectural deep dive into check-lock-execute-set mechanics and driver internals, see LEARN.md.
By default, the package uses the driver defined in config/cooldowns.php. You can switch drivers on the fly per request or action:
// Store transient rate checks in fast cache/Redis
Cooldown::for('api_ping', $ip)->using('cache')->for(30);
// Store billing/audit cooldowns persistently in SQL database
Cooldown::for('billing_charge', $user)->using('database')->for(86400);
// Direct driver instance access
$cacheDriver = Cooldown::driver('cache');
$cacheDriver->put('custom_key', 180);You can extend the CooldownManager with your own storage drivers (e.g., DynamoDB, MongoDB) in your AppServiceProvider:
use ZaberDev\Cooldown\Contracts\CooldownDriverContract;
use ZaberDev\Cooldown\Facades\Cooldown;
public function boot(): void
{
Cooldown::extend('redis-cluster', function ($app) {
return new MyRedisClusterCooldownDriver($app['redis']);
});
}When using the database driver, expired records are automatically marked for pruning via Laravel's Prunable trait on the ZaberDev\Cooldown\Models\Cooldown model.
To clean up old records automatically, schedule Laravel's model:prune command in your console.php or Kernel.php:
use Illuminate\Support\Facades\Schedule;
use ZaberDev\Cooldown\Models\Cooldown;
Schedule::command('model:prune', ['--model' => Cooldown::class])->daily();Whenever a cooldown is initiated or cleared, the package dispatches strongly typed events if enabled (cooldowns.events.dispatch = true):
ZaberDev\Cooldown\Events\CooldownInitiated: Dispatched whenfor()oruntil()creates a cooldown ($key,$expiresAt,$action,$target).ZaberDev\Cooldown\Events\CooldownReset: Dispatched whenreset()clears a cooldown ($key,$action,$target).
You can listen to these in your EventServiceProvider for logging, monitoring, or webhook triggers.
Laravel Cooldown includes built-in AI support and architectural skills engineered for Laravel Boost.
When using AI coding assistants (such as Cursor, Claude Code, or GitHub Copilot connected via the Boost MCP server), your AI agent can automatically load specialized design patterns and exact API rules for implementing rate limits and entity-scoped action cooldowns with our package.
When Laravel Boost (laravel/boost) is installed in your application, our package AI skill is automatically discovered and published during package installation and updates (php artisan boost:install or php artisan boost:update).
If you install laravel-cooldown into an existing Boost-enabled project, our service provider also automatically synchronizes the skill directly into your .ai/skills/laravel-cooldown directory on boot with zero configuration needed.
If you prefer to install or update the AI skill manually, you can use any of the following commands:
# Using Laravel Boost
php artisan boost:add-skill zaber-dev/laravel-cooldown
# Using Vendor Publish
php artisan vendor:publish --tag=cooldowns-skillBy enabling our skill, your AI assistant will strictly follow package conventions, including:
- Utilizing
Cooldown::for('action', $target)->block(...)for atomic in-flight execution and double-click race condition protection. - Applying
use ZaberDev\Cooldown\HasCooldowns;directly to Eloquent models ($user->cooldown('send_sms')->for('5 minutes')). - Selecting the proper storage driver (
cachefor high-throughput transient limits vsdatabasefor auditability and server-restart persistence). - Enforcing route middleware (
middleware('cooldown:action,duration')) that respects controller validation failures cleanly. - Handling
CooldownActiveException(HTTP 429) andRetry-Afterheaders idiomatically.
This package is part of the ZaberDev Laravel Ecosystem (Laravel Productivity Toolkit) — a cohesive suite of high-level application primitives engineered for concurrency, state management, and resource allocation.
Explore the complete directory of packages, detailed use cases, and documentation in our Ecosystem Index Hub.
Run the comprehensive PHPUnit test suite locally:
composer testThank you for considering contributing! Please ensure any pull requests include thorough PHPUnit tests covering unit, feature, and driver integration scenarios.
The MIT License (MIT). Please see LICENSE.md for more information.
Built with ❤️ as part of the ZaberDev Laravel Ecosystem.
