I've using DB::beginTransaction()
in Laravel but its working only for database changes that done in main function only not for sub functions.
Main function code:
try {
DB::beginTransaction();
$data = array(
'id' => Input::get('id'),
'task_title' => Input::get('task_title'),
);
DB::table('task')->insert($data);
$id = DB::getPdo()->lastInsertId();
// Add Actionees
if (!$this->addActionees(Input::get('actionees'), $id)) {
DB::rollback();
return Response::json(false);
}
DB::commit();
return Response::json(true);
} catch (Exception $ex) {
DB::rollback();
return Response::json($ex);
}
Sub function Code:
private function addActionees($actionees, $id, $status) {
try {
DB::table('task_assignee_user')->where('task_id', $id)->delete();
foreach ($actionees as $act) {
$actAdd = array(
'task_id' => $id,
'user_id' => $act->user_id,
);
DB::table('task_assignee')->insert($actAdd);
}
return True;
} catch (Exception $ex) {
return FALSE;
}
}
So in above example the changes that done under functions addActionees()
is not rolled back ,In function addActionees()
all record against ID will removed before inserting new records. If there is exception found then i want to revert these changes.
You should not catch the exception in addActionees() method. Just leave it thrown and the outer try-catch block will handle it:
Main function code:
try {
DB::beginTransaction();
$data = array(
'id' => Input::get('id'),
'task_title' => Input::get('task_title'),
);
DB::table('task')->insert($data);
$id = DB::getPdo()->lastInsertId();
// Add Actionees
$this->addActionees(Input::get('actionees'), $id);
DB::commit();
return Response::json(true);
} catch (Exception $ex) {
DB::rollback();
return Response::json($ex);
}
Sub function code:
private function addActionees($actionees, $id, $status) {
DB::table('task_assignee_user')->where('task_id', $id)->delete();
foreach ($actionees as $act) {
$actAdd = array(
'task_id' => $id,
'user_id' => $act->user_id,
);
DB::table('task_assignee')->insert($actAdd);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With