Laravel Database Transactions: How To Implement and Use Them Effectively?

laravel-logo

A database transaction is a set of operations that you can carry out securely within the database structure of your application, such as SQL queries to modify data (e.g. updates, deletions, and insertions).

At any point, you can decide to roll back all the transaction’s queries. In addition, any queries you make will be treated as a single action by the database.

Let’s look at an example of this.

Assume we have an app that enables users to create accounts. Naturally, there can be one or many users affiliated with each account. If this app simultaneously generates an account and the first user, you’ll have to deal with what happens if an account is generated properly, but the user isn’t.

// Create Account
$newAcct = Account::create([
  'accountname' => Input::get('accountname'),
]);

// Create User
$newUser = User::create([
  'username' => Input::get('username'),
  'account_id' => $newAcct->id,
]);

There are two scenarios here that can cause unpleasant issues:

  1. Account isn’t generated
  2. Failure to create a user

Let’s consider the latter situation.

Having an account with no available users leads to data inconsistency in the database. To resolve this, you can either go through the daunting task of coding around it or save a lot of code or simply wrap it up in a transaction to get things done quickly.

While database transactions are present in most SQL databases, they vary mainly in their implementation and efficiency. Popular systems such as MySql, SQLite, and Oracle support transactions, so you shouldn’t have trouble deploying your preferred SQL database.

Their three main Type of functions we need to implement in our code.

  • DB::beginTransaction();
  • DB::commit();
  • DB::rollback();

Check The Example of how transactions work in Laravel.

First include on Facades/DB.

use Illuminate\Support\Facades\DB;

Then include the

try {

    DB::beginTransaction();
    
    // Create Account
    $newAcct = Account::create([
      'accountname' => Input::get('accountname'),
    ]);
    
    // Create User
    $newUser = User::create([
      'username' => Input::get('username'),
      'account_id' => $newAcct->id,
    ]);
    
    DB::commit();
    
} catch (\Throwable $th) {
    DB::rollback();
    throw $th;
}

We pub DB::beginTransaction() at the start of inserting data into the database when it ends we use DB::commit. in case the code breaks the data will rollback and it will remove all the entries.

Reference document from Laravel official documentation.