Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel return value from within transactions

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;
    } // ...
}}
like image 951
Luis Lopez Avatar asked Nov 05 '17 17:11

Luis Lopez


1 Answers

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

like image 64
Jeffrey Avatar answered Oct 12 '22 15:10

Jeffrey