Ad

Laravel DB::transaction Exception PDO There Is No Active Transaction

i have the following code:

$new_models = DB::transaction(function () use ($supplier, $address, $addressDetail) {            
        $new_supplier = $this->setNewSupplier($supplier);
        $new_address = $this->setNewAddress($address);           
        $new_addressDetail = $this->setNewAddressDetail($addressDetail,$new_address->id);           
        $this->syncSupplierAddress($new_supplier->id,$new_address->id);
        $this->updateControlAp($new_supplier->supplier_id);   
        return [$new_supplier, $new_address, $new_addressDetail];
    });

The set methods are basically creating the models object with save() at the end; Now this works perfectly fine if 2nd...nth fails BUT NOT if the first one fails. If $this->setNewSupplier($supplier); fails than i get

"PDOException in Connection.php line 541:
There is no active transaction"

Am i doing something wrong here ? Also if i comment $this->rollBack(); from the catch in vendor Connection.php it actually gives me the SQL error. Important part here is that this isn't working only if first save() fails

PS. I am using PostgreSQL not MySQL but i don't think its related

Ad

Answer

There are different ways to make transactions in Laravel, another one could be this:

...
$new_models = [];
try {
  DB::beginTransaction();

  $new_supplier = $this->setNewSupplier($supplier);
  $new_address = $this->setNewAddress($address);           
  $new_addressDetail = $this->setNewAddressDetail($addressDetail,$new_address->id);           
  $this->syncSupplierAddress($new_supplier->id,$new_address->id);
  $this->updateControlAp($new_supplier->supplier_id);   
  $new_models = [$new_supplier, $new_address, $new_addressDetail];

  DB::commit();
} catch(\Exception $e) {
   DB::rollback();
   // Handle Error
}
...
Ad
source: stackoverflow.com
Ad