Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to a Laravel DB Transaction if an exception is thrown?

I think* the transaction is just discarded. Is this accurate?

I'm using mysql

Example:

try {
    DB::beginTransaction();
    throw new Exception("something happened");
    DB::commit()
} catch (Exception $e) {
    Log::debug("something bad happened");
}

Thanks

like image 676
timbroder Avatar asked Dec 19 '22 11:12

timbroder


1 Answers

If you are using in a Closure, like:

DB::transaction(function () {
    DB::table('users')->update(['votes' => 1]);
    DB::table('posts')->delete();
});

You'll run this code inside framework:

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;
    } catch (Throwable $e) {
        $this->rollBack();

        throw $e;
    }

    return $result;
}

So, in this case, you are 100% sure that the transaction is going to rollback. If you open manually transaction with DB::beginTransaction();, there is no way to be sure that is going to rollback, unless you make sure with something like:

try {
    DB::beginTransaction();
    //do something
    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
}

If you throw an exception without catch, the scripts die or end with opened transaction, PDO will automatically rollback (http://php.net/manual/en/pdo.transactions.php):

When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back.

like image 89
Felippe Duarte Avatar answered Mar 02 '23 00:03

Felippe Duarte