4.5 C
New York
Wednesday, November 30, 2022

How to use DB transactions in Laravel?





First, Let’s undestand why we are use transactions in laravel project. But db transactions is very important concept and very usefull because it securely manage. laravel 5 also provide to transactions commit, rollback etc functions. How to use transactions in my project, so I an going to give you one example, I have a three table “items”, “items_city” and “items_count” and i need to add new row same time and “items” table is a main table then “items_city” and “items_count” is a child table of “items” table. so bassically why we nee to use transactions because if when i was add new records in db then face error on “items_city” table insert time then “items” and “items_count” table records automatically rollback. But if all the tablee data successfully inserted then it will return true. you can check bellow example how to use it.

Example:

DB::transaction(function () {

$item_id = DB::table('items')->insertGetId(['title' => 'Hery']);

DB::table('items_city')->insert(['item_id'=>$item_id,'name' => 'India']);

DB::table('items_count')->insert(['item_id'=>$item_id,'price' => 10]);

});

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles