Laravel - Cache - Managing Locks

Atomic locks allow for the manipulation of distributed locks without worrying about race conditions. For example, Laravel Forge uses atomic locks to ensure that only one remote task is being executed on a server at a time. You may create and manage locks using the Cache::lock method:

    
    use Illuminate\Support\Facades\Cache;
    
    $lock = Cache::lock('foo', 10);
    
    if ($lock->get()) {
        // Lock acquired for 10 seconds...
    
        $lock->release();
    }
	

The get method also accepts a closure. After the closure is executed, Laravel will automatically release the lock:

    
    Cache::lock('foo')->get(function () {
        // Lock acquired indefinitely and automatically released...
    });
	

If the lock is not available at the moment you request it, you may instruct Laravel to wait for a specified number of seconds. If the lock can not be acquired within the specified time limit, an Illuminate\Contracts\Cache\LockTimeoutException will be thrown:

    
    use Illuminate\Contracts\Cache\LockTimeoutException;
    
    $lock = Cache::lock('foo', 10);
    
    try {
        $lock->block(5);
    
        // Lock acquired after waiting a maximum of 5 seconds...
    } catch (LockTimeoutException $e) {
        // Unable to acquire lock...
    } finally {
        optional($lock)->release();
    }
	

The example above may be simplified by passing a closure to the block method. When a closure is passed to this method, Laravel will attempt to acquire the lock for the specified number of seconds and will automatically release the lock once the closure has been executed:

    
    Cache::lock('foo', 10)->block(5, function () {
        // Lock acquired after waiting a maximum of 5 seconds...
    });