How to use DB transactions in laravel 5?

By Hardik Savani | March 6, 2016 | | 41767 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.

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

});



Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.