Hello Artisan 😎 , Database transactions are often an overlooked feature, but Laravel makes it so effortless.

One of the powerful ways to ensure data integrity is database transactions. Database transactions give a powerful ability to safely perform multiple database queries in a single transaction. If all queries run smoothly, then only it will commit otherwise it will roll back.

For Example, we have an application where we create a user, assign a role to the created user, and add KYC (Know your customer).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Creating a User
$user = User::create([
	// user data
]);


# Assigning a Role
$user->assignRole('customer');

# Creating kyc information for the user
Kyc::create([
	'user_id' => $user->id,
	// other info
]);

This all looks good. We don’t want any user without role and KYC but what if the user is not created. If the user is not created, we cannot assign a role and add KYC. This will cause errors in our system.

Here comes the Database transactions to the rescue :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
DB::transaction(function()
{
    # Creating a User
	$user = User::create([
		// user data
	]);


	# Assigning a Role
	$user->assignRole('customer');

	# Creating kyc information for the user
	Kyc::create([
		'user_id' => $user->id,
		// other info
	]);
});

As Laravel Documentation describes, all we have to do is wrap our database calls within a closure. If an Exception is thrown within the closure, then the transaction will roll back.

And that’s it ✌️ We’re done!