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