Blog

Laravel 5. Database Transactions

Transactions are vital part of modern databases. A transaction is a sequence of database operations on one or many tables, which are considered as a single (atomic) operation. If any of the operations in a transaction fails, the transaction is considered to have failed to be committed. In this case, the transaction can be rolled back, which will return the whole database to its initail state. Some may describe transactions in a more human friendly manner as "all-or-nothing".

Laravel 4 and Laravel 5 also support transactions. Their database layer depends on PDO, which provides transaction support. The official examples show how to use transactions using closires. However, I find closures to be painful to work with, and also terrible to read. So this is a small example of how to use transactions in Laravel 5 in a more development friendly way.

\DB::beginTransaction();
try{
    $item = new Item;
    $item->save();

    $itemAuthor = new ItemAuthor();
    $itemAuthor->item_id = $item->id;
    $itemAuthor->name = 'John Doe';
    $itemAuthor->save();

    \DB::commit();

    return $this->flashSuccess('Transaction was successfully committed');
} catch (Exception $e){
    \DB::rollback();
    return $this->flashError('Transaction failed.');
}

Hope you enjoyed the example. You can now proceed with your task at hand.

Happy coding.