Transaction not working for sub functions

Viewed 1240

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.

5 Answers
Related