How to use DB transactions in Laravel?

How to use DB transactions in Laravel?

In this post we will give you information about How to use DB transactions in Laravel?. Hear we will give you detail about How to use DB transactions in Laravel?And how to use it also give you demo for it if it is necessary.

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

});

Hope this code and post will helped you for implement How to use DB transactions in Laravel?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  50  =  53

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US