Search
 
SCRIPT & CODE EXAMPLE
 

PHP

Pessimistic Locking Laravel

<?php

function transfer($fromAccountId, $toAccountId, $amount)
{
  DB::beginTransaction();

  try {
    $fromQuery = Account::whereId($fromAccountId);
    if (! $fromQuery->exists()) {
      throw new InvalidAccountException();
    }

    $toQuery = Account::whereId($toAccountId);
    if (! $toQuery->exists()) {
      throw new InvalidAccountException();
    }

    $fromAccount = $fromQuery->lockForUpdate()->first();
    if ($amount > $fromAccount->balance) {
      throw new InsufficientBalanceException();
    }

    $toAccount = $toQuery->lockForUpdate()->first();
    $toAccount->balance += $amount;
    $toAccount->save();

    $fromAccount->balance -= $amount;
    $fromAccount->save();

    $transaction = new Transaction();
    $transaction->from_account_id = $fromAccountId;
    $transaction->to_account_id   = $toAccountId;
    $transaction->amount          = $amount;
    $transaction->save();

    DB::commit();
  } catch (Exception $e) {
    DB::rollBack();
    throw $e;
  }
}
Comment

PREVIOUS NEXT
Code Example
Php :: php check new month 
Php :: page.php woocommerce 
Php :: php-array-delete-by-value-not-key 
Php :: php readlink 
Php :: laravel api error return homepage 
Php :: laravel where json array column 
Php :: php typecast class 
Php :: iframe site bi link laravel 
Php :: strcmp php 
Php :: php superglobal - $globals 
Php :: how to delete a row in phpmyadmin 
Php :: if certain condition is met exit if block php 
Php :: socket io laravel 
Php :: php DateTime only date 
Php :: get data from stdclass object php 
Php :: laravel scope 
Php :: sass for php 
Php :: how to catch duplicate entry to database in laravel 
Php :: laravel relations find 
Php :: input if not null laravel 
Php :: php date time formatting 
Php :: eloquent relationships 
Php :: laravel gate 
Php :: Merging Two Laravel Collections keeping the original keys 
Php :: laravel scheduler every 10 minutes 
Php :: how to convert amount in words in php 
Php :: $age = 20; print ($age = 18) ? "Adult" : "Not Adult"; 
Php :: nested array in laravel 
Php :: if order has product id in array 
Php :: phpexcel set data type 
ADD CONTENT
Topic
Content
Source link
Name
9+3 =