ensureWalletHasEnoughFunds($wallet, $amount); } return DB::transaction(function () use ($wallet, $type, $amount, $reason, $transfer) { $transaction = $wallet->transactions()->create([ 'amount' => $amount, 'type' => $type, 'reason' => $reason, 'transfer_id' => $transfer?->id, ]); $this->updateWallet($wallet, $type, $amount); return $transaction; }); } /** * @throws Throwable */ protected function updateWallet(Wallet $wallet, WalletTransactionType $type, int $amount): void { if ($type === WalletTransactionType::CREDIT) { $wallet->increment('balance', $amount); } else { $wallet->decrement('balance', $amount); } } /** * @throws InsufficientBalance */ protected function ensureWalletHasEnoughFunds(Wallet $wallet, int $amount): void { if ($wallet->balance < $amount) { throw new InsufficientBalance($wallet, $amount); } } }