Back

Transactions not running multiple queries


angujo posted 2 months ago

Am trying out transactions on Laravel. My code is as below;

try {
            \DB::connection('db1')->transaction(function () use ($programme, $request) {
                if ($s = $programme->save()) {
                    if (empty($request->supervisors) || !is_array($request->supervisors)) throw new Exception('A programme should have at least one supervisor!');
                    Supervisor::where('programme_id', $programme->id)->whereNotIn('office_id', $request->supervisors)->delete();
                    foreach ($request->supervisors as $supervisor) {
                        Supervisor::updateOrCreate(['programme_id' => $programme->id, 'office_id' => $supervisor], ['programme_id' => $programme->id, 'office_id' => $supervisor]);
                    }
                }
                JsonResult::result($s, 'Programme successfully saved!', 'Error encountered while saving the programme!', Hashids::encode($programme->id));
            });
        } catch (Exception $exception) {
            JsonResult::error($exception->getMessage());
        }

When I run above with supervisors, it returns successful but neither the supervisor nor programme is updated or inserted but it returns success at the end.

If no supervisor then an error is thrown as expected with no update/entry in the tables.

Both supervisor and programme models use the db1 connection indicated.

What am I missing here?

Thanks in advance


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us