Home > other >  laravel db transaction context is available on called functions
laravel db transaction context is available on called functions

Time:05-14

I have found that for using DB::transaction in Laravel, in combination with the ORM, we need to run something like:

DB::transaction(function() {
      //
   Model::create($something);
});

My question is: If i need to call other function from inside the closure, that runs other creation method, there will be in the "transaction" enviroment or is it outside?

DB::transaction(function() {
      //
   ModelX::create($something);
   $this->somefunction($data);
});

private function somefunction($data){

    ModelY::create($data) <----this create is in the transaction or do I need a new one for having rollback in case of errros?

}

CodePudding user response:

Remember that your code can use any additional functions/methods that will not return redirect. This will skip commit() or rollback(). Once the beginTransaction() started it has to end with commit() or rollback().

    DB::beginTransaction();
    try {
       /* your code */
       /* you can also use DB::commit(); at the end of TRY code like this */
    } catch (\Exception $ex) {
       DB::rollback();
       /* handle error */
       /* use return after rollback() */
    }
    DB::commit();

    /* use return after commit(); */

CodePudding user response:

after several test i can tell that no closure is needed for model too, even if you have a create method inside another function, and exception is throwed -in the main or in the function- no problem with the rollback and commit steatment! Well much more of that i was hoping!!!!

This is the code I tested:

   DB::beginTransaction();
        try {
            $this->pippo();
        } catch (\Exception $ex) {
            DB::rollback();
        }
   DB::commit();

public function pippo(){
    $type=Cga_type::create(['name'=>'vvvv','description'=>'yyy']);
    throw new Exception('error');

}

If I comment the transactions functions the record is written on the db, no otherwise!!!

  • Related