How to use DB transactions in Laravel?

By Hardik Savani September 30, 2022 Category : PHP Laravel

Hello,

This article is focused on how to use db transaction in laravel. you will learn db transaction laravel example. This article goes in detailed on how use database transactions laravel. It's a simple example of laravel db transaction try catch. Let's see below example laravel eloquent database transactions.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions.

Sometimes, we need to store data in tables with table dependency. For example, i created users, users_profile and users_address tables. When I will create a new user then I just need to store data in the profile and address tables as well. But if there is any cause to adding wrong format data or if anything happens then it can be a problem to store data in the dependent table. However, laravel eloquent added database transactions, so whenever we have an error or issue then it will roll back the database entry.

Let's see the code of how to use db transaction in laravel.

Example Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

use Exception;

use App\Models\User;

use App\Models\UserProfile;

use App\Models\UserAddress;

class UserController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function store(Request $request)

{

try {

/*------------------------------------------

--------------------------------------------

Start DB Transaction

--------------------------------------------

--------------------------------------------*/

DB::beginTransaction();

/* Create New User */

$user = User::create([

'name' => $request->name,

'email' => $request->email,

'password' => bcrypt($request->password)

]);

/* Create New User Profile */

$userProfile = UserProfile::create([

'user_id' => $user->id,

'birthdate' => $request->birthdate,

'gender' => $request->gender,

'phone' => $request->phone,

]);

/* Create New User Address */

$userAddress = UserAddress::create([

'user_id' => $user->id,

'address' => $request->address,

'city' => $request->city,

'state' => $request->state0,

]);

/*------------------------------------------

--------------------------------------------

Commit Transaction to Save Data to Database

--------------------------------------------

--------------------------------------------*/

DB::commit();

} catch (Exception $e) {

/*------------------------------------------

--------------------------------------------

Rollback Database Entry

--------------------------------------------

--------------------------------------------*/

DB::rollback();

throw $e;

}

}

}

I hope it can help you...

Tags :