How can I use db transaction in laravel?
You can't add return
statement inside transaction
that halts entire process and DB::rollback()
is executed.
To switch the 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 }}
Hope you understand.
You can use it like this:
$returnResult = [];DB::beginTransaction();try { ... DB::commit(); $returnResult['status'] = true; $returnResult['data'] = $status;} catch (...) { ... DB::rollback(); $returnResult['status'] = true; $returnResult['message'] = $e->getMessage();}return $returnResult;