Laravel return value from within transactions
Asked Answered
A

3

10

I'm working with transactions in laravel 5, so far I have been getting the results of any method outside of the statement with a reference param &$, but I red this is a bad practice because the operator & is obsolete. Is there any other way to get the value of a var outside transaction scope?

this is a code example:

public function post(Request $request, Persona $persona)
{
    try {
        DB::transaction(function () use ($request, &$result) {          
            $result = Persona::create($request->all());
            // ... Moooore code omitted 
        });

        // Do more thing with $result 
        $result;
    } // ...
}}
Anthology answered 5/11, 2017 at 17:47 Comment(0)
S
10

Use DB::beginTransaction() and DB::commit() instead:

DB::beginTransaction();
try {
    $result = Persona::create($request->all());
    DB::commit();
} catch (Exception $e) {
    DB::rollBack();
}

Laravel 5.5: Database Transactions

Septuple answered 5/11, 2017 at 17:58 Comment(1)
This answer should not selected as answer. you can return the required value directly from within the closure. please refer to github.com/laravel/framework/blob/5.3/src/Illuminate/Database/… as recommended by laracasts.com/discuss/channels/tips/…Refugio
M
3

It's not that complicated, just return the result inside your transaction ;)

public function post(Request $request, Persona $persona)
{
    try {
        $result = DB::transaction(function () use ($request) {          
            $result = Persona::create($request->all());
            // ... Moooore code omitted 
            return $result;
        });

        // Do more thing with $result 
        $result;
    } // ...
}}
Monotype answered 5/11, 2017 at 21:37 Comment(3)
No, return inside transactions is not working for me!!Anthology
You can't return from the closure. You'd have to pass in (by reference) a variable to modify.Celluloid
This perfectly work and should be selected as the correct answer. you can return the required value directly from within the closure. please refer to github.com/laravel/framework/blob/5.3/src/Illuminate/Database/… as recommended by laracasts.com/discuss/channels/tips/…Refugio
P
0
$someVal = DB::transaction(function () {
    return $something;
});

print($someVal);

DB::transaction returns what you returns inside closure.

Preside answered 7/9, 2022 at 12:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.