Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction not working for sub functions

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.

like image 774
Govind Samrow Avatar asked Aug 01 '17 13:08

Govind Samrow


1 Answers

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);
        }
}
like image 65
Murat Tutumlu Avatar answered Nov 20 '22 04:11

Murat Tutumlu