Latest

Tuesday, July 11, 2017

How to execute a block of php code if a transaction using eloquent fails (Laravel 5.3)?

Asked by: Diego Alves


I want to remove the directory that gets created when I record in the database is inserted. I have something like this.

$model->dir = MyClass->createDirectory();

\DB::transaction(function(){ 
    $model->save(); // fails        
});
MyClass->removeDirectory(); //this will be execute upon failure.

I'm not asking about try catch block with transactions. I am asking how to execute a block of code if transaction fails.


Answers

Answered by: Sagar Gautam at 2017-07-11 08:33PM



Delete the directory created after rollback in the transaction using try catch.

DB::beginTransaction();

try{

    $model->save();

    DB::commit();

}catch(\Exception $e){

    DB::rollback();

   // After rollback delete directory created
   // write code to delete directory here.
}



Source

No comments:

Post a Comment

Adbox