How to use DB transactions in laravel 5?

By Hardik Savani | March 6, 2016 | | 4320 Viewer | Category : PHP 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.


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]);