enchance enchance - 9 months ago 55
PHP Question

Laravel DB::transaction() return value

It's my first time to use

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
, or if it fails will the method either return
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


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


I wrote down this solution for others who might be wondering.

Since I was more concerned about returning a boolean value depending on the success of my query, with a few modifications it now returns
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
is never returned since if something goes wrong with your query, the
is immediately triggered returning
. Thanks to @ilaijin for showing that an
object is thrown if something goes wrong.


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

public function transaction(Closure $callback)

    // 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.
        $result = $callback($this);


    // 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)

        throw $e;

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