Click Below to subscribe

How To Implement Database Transactions in Laravel 2020

Transaction is a way to execute or commit a group of operations as a unit. In other words, it is a technique to call multiple SQL statements as a single unit.

In case of the transaction if any error occurred all the operations rollback.

Laravel provides a very easy way to implement transactions.

# Without Transaction

// Create User
$user = User::create([
    'name' => 'Van Helsing',
]);

// Create Shipping Address
$address = ShippingAddress::create([
    'address' => 'Any Address',
    'user_id' => $user->id,
]);

In the above example, we can face two error cases.

1.  user creation operation is not executed.

2.  user is created but shipping address operation is not executed.

So to prevent this type of scenario we need to use transactions.

# Transactional Toolset

1. Creating a transaction

2. Rollback a transaction

3. Committing a transaction

# Implementation

1. Using transaction() method

DB::transaction(function () {
    // Create User
    $user = User::create([
        'name' => 'Van Helsing',
    ]);

    // Create Shipping Address
    $address = ShippingAddress::create([
        'address' => 'Transylvania',
        'user_id' => $user->id,
    ]);
});

In this way, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the transaction method

# Note:- we can also pass parameters in the transaction() method.

DB::transaction(function () use($data){
    // Create User
    $user = User::create([
        'name' => $data->name,
    ]);

    // Create Shipping Address
    $address = ShippingAddress::create([
        'address' => $data->address,
        'user_id' => $user->id,
    ]);
});

2. Using manual actions (Recommended)

In this way, we have more control over the operations. so I personally prefer this way to implement transactions. we have three methods for manually controlling the operations. we need to use DB facade for calling transaction methods.

DB::beginTransaction();  // for starting a new transaction
DB::rollBack();          // for rollback the operations
DB::commit();            // for committing all operations

DB::beginTransaction();

try {
    // Create User
    $user = User::create([
        'name' => 'Van Helsing',
    ]);
} catch(Exception $e) {
    // here you can handle errors
    DB::rollBack();
}

try {
    // Create Shipping Address
    $address = ShippingAddress::create([
        'address' => 'Transylvania',
        'user_id' => $user->id,
    ]);
} catch(Exception $e) {
    // here you can handle errors
    DB::rollBack();
}

DB::commit();  // if everything goes fine then commit

In the above example, we have full control over the operation so we can easily handle errors based on what error occurred.

Leave Your Comment