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 :)
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();
}
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();
});
Thanks .... 100% .... I was missing the &$var .....
Thanks. Your idea solve my problem
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);
Or you can simplify even more:
return DB::transaction(function () {
// ...logic here
return someGetResult();
});
@Magalliu
Or even simpler:
//
Nah. just kidding :)
Please sign in or create an account to participate in this conversation.