I'm bothered by this code
if (!$lock->get()) {
throw new Exception('Cant send cash at the moment, please try again later');
}
if ($lock->get()) {
In the first lock->get() this should succeed, but then the second will fail because you already got a lock. Not sure you are doing it this way? I would take out the second if entirely
and you are missing the catch in your try-catch
Following the laravel docs;
$lock = Cache::lock('transferCash_'. $sender->id . '_lock', 10);
try {
$lock->block(5);
$sender->refresh();
$receiver->refresh();
$sender->wallet->refresh();
$receiver->wallet->refresh();
$this->logTransaction(
sender: $sender,
receiver: $receiver,
amount: $request['amount'],
action: ' locked send cash transaction for ',
state: "old"
);
$this->checkSenderHasEnoughBalance(
senderBalance: $sender->wallet->balance,
amountInNairaToBeSent: $request['amount']);
$sender->transferCash(receiver: $receiver,
amount: $request['amount'],
description: 'Send cash to ' . $receiver->username,
type: 'send_cash');
} catch (LockTimeoutException $e) {
throw new Exception('Cant send cash at the moment, please try again later');
} finally {
$lock?->release();
$this->logTransaction(
sender: $sender,
receiver: $receiver,
amount: $request['amount'],
action: ' released locked send cash transaction for ',
state: "new"
);
}