support@codebucket.net

How To Add try...catch with DB::transaction() in Laravel

How To Add try...catch with DB::transaction() in Laravel

K. M. Shawkat Zamil | January 24, 2023

Hello Developers,

 

In this demonstration, I will show how to add try-catch with DB::transaction() in Laravel. In the try block, we write code to be executed, if any exception occurs then we will find it in the catch block.

 

Another thing is, DB:transaction(). It is used to make correct recovery from failure. Let's see how we use it.

 

For using try catch we can add the following block of code in the controller:

 

try {
    
    // all good

} catch (\Exception $e) {
    
    return $e->getMessage();

}

 

For using DB:transaction(), We can add the below block of code in the controller:

 

DB::beginTransaction();

if([condition]){
    
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();

else{

    DB::rollback();

}

 

If we combine the try...catch and the DB::transaction(), the code looks like this:

 

DB::beginTransaction();

try {

    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();


} catch (\Exception $e) {

    DB::rollback();

    return Log::info($e->getMessage());
}

 

I hope this might help in the journey of development.

 

Read More: What Is A Trait in PHP

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.