optimistic locking laravel

Solutions on MaxInterview for optimistic locking laravel by the best coders in the world

showing results for - "optimistic locking laravel"
Giada
30 Mar 2018
1<?php
2
3function transfer($fromAccountId, $toAccountId, $balance)
4{
5  $fromQuery = Account::whereId($fromAccountId);
6  if (! $fromQuery->exists()) {
7    throw new InvalidAccountException();
8  }
9
10  $toQuery = Account::whereId($toAccountId);
11  if (! $toQuery->exists()) {
12    throw new InvalidAccountException();
13  }
14
15  do {
16    $fromAccount = $fromQuery->first();
17    if ($fromAccount->balance < $amount) {
18      throw new InsufficientBalanceException();
19    }
20    $updated = Account::whereId($fromAccountId)
21      ->where('updated_at', '=', $fromAccount->updated_at)
22      ->update(['balance' => $fromAccount->balance - $amount]);
23  } while (! $updated);
24
25  do {
26    $toAccount = $toQuery->first();    
27    $updated = Account::whereId($toAccountId)
28      ->where('updated_at', '=', $toAccount->updated_at)
29      ->update(['balance' => $toAccount->balance + $amount]);
30  } while (! $updated);
31
32  $transaction = new Transaction();
33  $transaction->from_account_id = $fromAccountId;
34  $transaction->to_account_id   = $toAccountId;
35  $transaction->amount          = $amount;
36  $transaction->save();
37}