Hello developers in this tutorial we will discuss about how to handle errors in laravel using db::transaction
|1||What is DB::transaction|
|2||How to use 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 .
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::transactionCopy
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();
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.