Error handling using db::transaction in laravel 10 , handle error in laravel 10

Error handling using db::transaction in laravel 10 , handle error in laravel 10

14-Sep-2024
| |
Image Carousel

Hello developers in this tutorial we will discuss about how to handle errors in laravel using db::transaction

Table of Contents

S.no Contents-topics
1 What is DB::transaction
2 How to use DB::transaction
3 Error Handling

1:What is DB::transaction

DB::transaction is a feature provided by laravel to rollback the database queries if any error occurs , for eg mostly likely to happen with fintech companies when a transaction is occur but due to some technical issues payment has been cancelled but at that time payment has been deducted from sender bank account and in our database it also shows success but payment doesn't recieved at the sender end , so at this time db::transaction has been used so that if any error occurs it rollback all the database queries .

2:How to use DB::transaction 

In laravel to use DB::transaction always use it in try => catch block as to handle error when query falls in catch block
Code for db::transaction
Copy

public function db_transaction()
   {
    try {
        DB::beginTransaction(); //make this block observable and process start
        $user = new User();
        $user->name = 'developer';
        $user->email = '[email protected]';
        $user->password = '132';
        $user->save();
 
        $user = User::find(99999999);
        $user->name = 'dev';
        $user->save();
        DB::commit(); //process end
        echo "No Error occurs";
    } catch (\Throwable $th) {
        //throw $th;
        DB::rollBack(); // if error occurs rollback all database queries
        echo $th;
    }
   }

As shown in code  DB::beginTransaction(); initiate to tell the code where to start observing the code and    DB::commit(); work as end point like we have two points start and end point , inbetween these two points we make our process observable because later on if ay error occurs in catch block it will rollback all the queries using DB::rollBack();

3:Error Handling

In the above example we are making an error to hit the catch block as shown we are finding an id 9999999 that may not exist and it returns an error and rollback the whole query from database.

Tags: error handling using db::transaction in laravel 10 , handle error in laravel 10 , db transaction in laravel 10 , what is db transaction in laravel 10,laravel , php ,laravel-php , mvc laravel, advance laravel , bugs in laravel , laravel advance level,
0 Comments (Please let us know your query)
Leave Comment
Leave Comment
Articles from other Categories
Load More

Newsletter