PHP code example of zaber-dev / laravel-cooldown

1. Go to this page and download the library: Download zaber-dev/laravel-cooldown library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zaber-dev / laravel-cooldown example snippets


Cooldown::for('password_reset', $user)
    ->for(300);

Cooldown::for('password_reset', $user)
    ->enforce();

return [
    /*
    |--------------------------------------------------------------------------
    | Default Storage Backend
    |--------------------------------------------------------------------------
    |
    | 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,
    ],
];

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...
}

// Throws CooldownActiveException (HTTP 429) if active or mid-flight, automatically attaching 'Retry-After' header
Cooldown::for('login_attempt', $user)->enforce();

Cooldown::for('send_otp', $user)->block(function () use ($otpService, $user) {
    $otpService->send($user->phone);
}, duration: 120);

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();

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use ZaberDev\Cooldown\HasCooldowns;

class User extends Authenticatable
{
    use HasCooldowns;
}

$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();

// 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();

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');

// 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);

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']);
    });
}

use Illuminate\Support\Facades\Schedule;
use ZaberDev\Cooldown\Models\Cooldown;

Schedule::command('model:prune', ['--model' => Cooldown::class])->daily();
bash
php artisan vendor:publish --provider="ZaberDev\Cooldown\CooldownServiceProvider"
bash
php artisan migrate
bash
# Using Laravel Boost
php artisan boost:add-skill zaber-dev/laravel-cooldown

# Using Vendor Publish
php artisan vendor:publish --tag=cooldowns-skill