How to use DB transactions in Laravel?

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

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



Recent Posts

Related Posts