6.6. Transactions

Now let us talk a little about transactions. Without going into the fine detail, I will demonstrate how transactions and the Eloquent ORM can be used together.

  1. DB::transaction(function () {
  2. // Create a new position in the invoice
  3. $line = new App\InvoiceLine();
  4. $line->CUSTOMER_ID = 45;
  5. $line->PRODUCT_ID = 342;
  6. $line->QUANTITY = 10;
  7. $line->COST = 12.45;
  8. $line->save();
  9. // add the sum of the line item to the amount of the invoice
  10. $invoice = App\Invoice::find($line->CUSTOMER_ID);
  11. $invoice->INVOICE_SUM += $line->SUM_PRICE;
  12. $invoice->save();
  13. });

Every parameter of the transaction method that is located inside the callback function is executed within one transaction.