15

It's my first time to use DB::transaction() but how exactly does it work if a transaction fails or is successful? In the example below, do I have to manually assign a value to return true, or if it fails will the method either return false or totally exit the transaction (therefore skipping the rest of the code)? The docs aren't so helpful on this.

use Exception;
use DB;

try {
    $success = DB::transaction(function() {
        // Run some queries
    });

    print_r($success);

} catch(Exception $e) {
    echo 'Uh oh.';
}
0

4 Answers 4

15

By giving a look at function transaction it does its process inside a try/catch block

public function transaction(Closure $callback)
{
    $this->beginTransaction();

    // We'll simply execute the given callback within a try / catch block
    // and if we catch any exception we can rollback the transaction
    // so that none of the changes are persisted to the database.
    try
    {
        $result = $callback($this);

        $this->commit();
    }

    // If we catch an exception, we will roll back so nothing gets messed
    // up in the database. Then we'll re-throw the exception so it can
    // be handled how the developer sees fit for their applications.
    catch (\Exception $e)
    {
        $this->rollBack();

        throw $e;
    }

So throws an Exception (after the rollback) if fails or returns $result, which is the result of your callback

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to simulate a failed transaction?
meaning u want to catch catch(Exception $e) { echo 'Uh oh.'; } ?
Sorry, no need. I momentarily forgot about throw.
5

There is a short version if you want to use the default transaction method that ships with Laravel without handling it manually.

$result = DB::transaction(function () { 
    // logic here
    return $somethingYouWantToCheckLater;
});

Comments

0

You can also use the following

DB::rollback();

Comments

0

(Posted on behalf of the question author, to move the solution to the answer space).

Since I was more concerned about returning a boolean value depending on the success of my query, with a few modifications it now returns true/false depending on its success:

use Exception;
use DB;

try {
  $exception = DB::transaction(function() {
    // Run queries here
  });

  return is_null($exception) ? true : $exception;

} catch(Exception $e) {
    return false;
}

Take note that the variable $exception is never returned since if something goes wrong with your query, the catch is immediately triggered returning false. Thanks to @ilaijin for showing that an Exception object is thrown if something goes wrong.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.