arnoldp's avatar

How do I return a value from a call to DB::transaction(function () use() { ... } );

I am using the DB transaction mechanism to keep my updates to MySQL "co-ordinated" ... Works like a dream .... However .... How can I return a value from within the function? I am using use() to pass parameters into the function, but can seem to get a variable "out" .... Please HELP :)

0 likes
8 replies
SaeedPrez's avatar

You don't have to use the function.. I like more control..

DB::beginTransaction();

$result = Model::where('foo', 'bar')->delete();

if ( $all == 'good' ) {
    DB::commit();
} else {
    DB::rollBack();
}
sayla's avatar

Alternatively, you can do the following:

$result = null;
DB::transaction(function () use(&$result) { 
    // logic here
    $result = someGetResult();
});
if ($result != null) {

}

However, according to https://github.com/laravel/framework/blob/5.3/src/Illuminate/Database/Connection.php#L561 (and from what I saw in 4.2 code) You should be able to get the return value directly.

$result = DB::transaction(function () { 
    // logic here
    return someGetResult();
});
17 likes
arnoldp's avatar

Thanks .... 100% .... I was missing the &$var .....

rodrigo.pedra's avatar

Actually the DB::transaction(...) returns whatever is returned from the callback.

So you could simplify it to:

$result = DB::transaction(function ()  { 
    // ...logic here

    return someGetResult();
});

dd($result);
5 likes
Magalliu's avatar

Or you can simplify even more:

return DB::transaction(function ()  { 
    // ...logic here

    return someGetResult();
});
5 likes

Please or to participate in this conversation.