Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hameti's avatar

DB::beginTransaction() ... DB::commit()

I am asking this because there is little information on the web about it.

The question is about the gain in terms of speed/performance when using transactions vs individual queries. Is it really a gain in it for us and does it worth rewriting queries in raw and use transactions?

0 likes
7 replies
LaryAI's avatar
Level 58

Well, if you're looking for a performance boost, you could always try using a DeLorean and a flux capacitor. But if you're looking for a more practical solution, then yes, using transactions can be a great way to improve the speed and performance of your queries. Just make sure you don't forget to hit the DB::commit() button when you're done!

1 like
click's avatar
click
Best Answer
Level 35

beginTransaction & commit is not related to writing raw queries or not. The result of eloquent's query builder are just queries.

Database transactions can definitely speed up some type of requests, for example mass insert requests. If this applies to your project is hard to say.

Another benefit of database transactions is that if you run multiple insert, update or delete queries and an exception pops up somewhere all of the queries will be reverted. This helps making sure your data is not left in an inconsistent state.

https://laravel.com/docs/10.x/database#database-transactions

1 like
hameti's avatar

@click thanks. Do you mean that I can use something like:

DB::beginTransaction() .
DB::table('users')->where('id',id1)->update('SOMETHING1','XX1');
DB::table('users')->where('id',id2)->update('SOMETHING2','XX2');
DB::table('users')->where('id',id3)->update('SOMETHING3','XX3');
DB::commit()

Why I was thinking that we must use DB::update/DB::insert with transactions?

click's avatar

@hameti yes, if one of the queries fail all of the update queries will be reverted.

I like using the closure variant:

DB::transaction(function(){
   DB::table('users')->where('id',id1)->update(['SOMETHING1' => 'XX1']);
   DB::table('users')->where('id',id2)->update(['SOMETHING1' => 'XX2']);
   DB::table('users')->where('id',id3)->update(['SOMETHING1' => 'XX3']);
});
1 like
Npdlink352's avatar

Do I have to do DB::commit() if I am not using DB::transaction(function(){ });

???????

Please or to participate in this conversation.