PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 3, 2022

[FIXED] What is the difference between DB::beginTransaction() and DB::transaction()?

 February 03, 2022     laravel, laravel-5.2, mysql, php, transactions     No comments   

Issue

I'm using Laravel 5.2.

I would like to know what are the differences between :

  1. DB::beginTransaction() and DB::transaction()
  2. DB::commitTransction() and DB::commit()
  3. DB::rollbackTransction() and DB::rollback()

Any helps would be appreciated.


Solution

DB::beginTransaction() will only begin a transaction, while for DB::transaction() you must pass a Closure function that will be executed inside a transaction.

So this:

DB::transaction(function() {
    // Do something and save to the db...
});

is the same as this:

// Open a try/catch block
try {
    // Begin a transaction
    DB::beginTransaction();

    // Do something and save to the db...

    // Commit the transaction
    DB:: commitTransaction();
} catch (\Exception $e) {
    // An error occured; cancel the transaction...
    DB::rollback();
    
    // and throw the error again.
    throw $e;
}

As you can see, DB::transaction() is a "helper" function to avoid writing code to catch errors, begin a transaction, commit the transaction, and optionally rollback (cancel the transaction) if an error occured.

If you have a more complex logic, or need an specific behaviour, you will manually build your transaction; if your logic is rather simple, DB::transaction() is the way to go.

As for DB::commitTransaction() and DB::rollbackTransaction(), I can't find information.

It's a good practice to check the source code of the things you use, because you will learn how they are written, as well as how to write. Here's the file with the source for these methods.



Answered By - Parziphal
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing