1. Go to this page and download the library: Download zaber-dev/laravel-lock 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/ */
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use ZaberDev\Lock\HasLocks;
class User extends Authenticatable
{
use HasLocks;
}
$user = User::find(1);
// Acquire a 60-second lock on "billing_charge" for this user
if ($user->lock('billing_charge')->ttl(60)->acquire()) {
try {
// Charge user...
} finally {
$user->lock('billing_charge')->release();
}
}
// Check status
if ($user->lock('billing_charge')->isLocked()) {
return response()->json(['message' => 'Action locked.'], 429);
}
// Get all database lock records assigned to this user
$activeLocks = $user->locks()->where('expires_at', '>', now())->get();
// Delete all lock records for this user
$user->locks()->delete();
use Illuminate\Support\Facades\Route;
// Enforce a 30-second lock on billing endpoints per User / IP address
Route::post('/billing/charge', [BillingController::class, 'charge'])
->middleware('lock:billing_charge,30');
// Use a specific storage engine
Route::post('/api/payout', [PayoutController::class, 'store'])
->middleware('lock:payout,60,database');
// Store transient mutex checks in fast cache/Redis
Lock::for('api_sync', $ip)->using('cache')->ttl(15)->acquire();
// Store critical transaction locks inside persistent database tables
Lock::for('account_transfer', $user)->using('database')->ttl(120)->acquire();
use ZaberDev\Lock\Contracts\LockDriverContract;
use ZaberDev\Lock\Facades\Lock;
public function boot(): void
{
Lock::extend('redis-cluster', function ($app) {
return new MyRedisClusterLockDriver($app['redis']);
});
}
use Illuminate\Support\Facades\Schedule;
use ZaberDev\Lock\Models\LockModel;
Schedule::command('model:prune', ['--model' => LockModel::class])->daily();