How to use DB transactions in Laravel?

Today now in this post i will show you how to use DB transactions in laravel. At first, Let’s need to know why we are use transactions in laravel project. We know db transactions is a very important concept and very useful because it is securely manage. laravel also provide to the transactions commit, rollback etc functions. we you will know How to use transactions in any project, so now I an going to give you one example, I have a three table “items”, “items_city” and “items_count” and then i need to add a new row same time and “items” table is a main table then the “items_city” and “items_count” is a child table of “items” table. So it is basically why we nee to use transactions because if when i was try to add a new records in db then i was face error on “items_city” table insert time then “items” and “items_count” table records automatically rollback. But if all the table data successfully inserted then it will return us true. we can check bellow example how we can 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]);

Read Also :Laravel Join with Subquery in Query Builder Example

Thanks for read. I hope it help you. For more you can follow us on facebook.


About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →