Database rollback transactions in Laravel

In this post I will show you an example of database rollback in Laravel application. Rolling back database changes in your Laravel application is required when you have many db operations to run in the process of completing a particular request. Sometime, it does not go well in the process and some of the db transactions may fail due to which you may need to rollback database changes already been made.
Consequently you have to rollback all the transactions done in the process which otherwise are going to make your system corrupt of break things.
In order to rollback your Laravel database queries all you need to do is to write some useful Laravel db code provided with database system modules.

There are two different ways to do the rollback

1. Calling inbuilt methods.

Include at the top

use Illuminate\Support\Facades\DB;

Just before staring your database transactions such as insert, updates or deletes call:

In the consequent lines you can use your code to do insert, updates or delete calls, such as:
........your code so process an order etc.
.......updated user status etc.
If some of the operation does not go well, we can make the flag the $commit as false;
if( something did not go well){
    $commit = false;

Since we have wrapped all our actions within a TRANSACTION wrapper when we called DB::beginTransaction();we have to commit it in order to take into effect or just rollback.

if ($commit) {
} else {

Also we can use raw mysql statements to do it.

2. Using mysql statements

Just before staring your database transactions such as insert, updates or deletes call this statement
DB::statement("START TRANSACTION;");
 …….you other db operations

And finally commit changes or rollback

if ($commit) {
    DB::statement("UNLOCK TABLES;");
} else {
    DB::statement("UNLOCK TABLES;");

You can also wrap transactions using try catch as shown below.

I hope it helps someone!

Leave a Reply