0

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.

Diego Alves
  • 2,462
  • 3
  • 32
  • 65
  • 1
    Possible duplicate of [Laravel: Using try...catch with DB::transaction()](https://stackoverflow.com/questions/22906844/laravel-using-try-catch-with-dbtransaction) – Maraboc Jul 11 '17 at 15:08
  • I'm not asking about try catch block with transactions. I am asking how to execute a block of code if transaction fails. – Diego Alves Jul 11 '17 at 15:36
  • It's the same thing but in your case in the `catch` block execute a block of code that you want ! or am i messing something? – Maraboc Jul 11 '17 at 15:48

1 Answers1

0

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.
}
Sagar Gautam
  • 9,049
  • 6
  • 53
  • 84