How can I use db transaction in laravel?

I try this:

public function destroy($id) { DB::beginTransaction(); try { $product = $this->product_repository->find($id); $result = $product->categories()->detach(); if($result) { list($status,$instance) = $this->product_repository->delete($id); } DB::commit(); return ['status'=>true,'data'=>$status]; } catch (\Exception $e) { DB::rollback(); return ['status'=>false, 'message'=>$e->getMessage()]; } } 

If the code is executed, $this->product_repository->delete($id) does not work / cannot be deleted.

But this is: $product->categories()->detach(); It is deleted / deleted.

How if product deletion failed, delete category also failed?

+1
php laravel transactions
source share
2 answers

You cannot add a return inside transaction , which stops the whole process and DB::rollback() is executed.

To switch return , you can define a boolean variable and make false while you catch exception.

Like this:

 public function destroy($id) { $success = true; DB::beginTransaction(); try{ // Your Code $product = $this->product_repository->find($id); $result = $product->categories()->detach(); if($result) { list($status,$instance) = $this->product_repository->delete($id); } DB::commit(); }catch(\Exception $e){ DB::rollback(); $success = false; } if($success){ // Return data for successful delete } else{ // Return data for unsuccessful delete } } 

I hope you understand.

+1
source share

You can use it as follows:

 $returnResult = []; DB::beginTransaction(); try { ... DB::commit(); $returnResult['status'] = true; $returnResult['data'] = $status; } catch (...) { ... DB::rollback(); $returnResult['status'] = true; $returnResult['message'] = $e->getMessage(); } return $returnResult; 
0
source share

All Articles