disableExistingRecord($user->currentCompany->id, $model, $uniqueField, $uniqueFieldValue); } else { $this->ensureAtLeastOneEnabled($user->currentCompany->id, $model, $enabled, $uniqueField, $uniqueFieldValue); } $data['enabled'] = $enabled; return $model::create($data); }); } catch (ValidationException) { throw new Halt('Invalid data provided. Please check the form and try again.'); } catch (AuthorizationException) { throw new Halt('You are not authorized to perform this action.'); } catch (Throwable) { throw new Halt('An unexpected error occurred. Please try again.'); } } protected function disableExistingRecord(int $companyId, Model $model, ?string $uniqueField = null, ?string $uniqueFieldValue = null): void { $query = $model::query()->where('company_id', $companyId) ->where('enabled', true); if ($uniqueField && $uniqueFieldValue) { $query->where($uniqueField, $uniqueFieldValue); } $existingEnabledRecord = $query->first(); if ($existingEnabledRecord !== null) { $existingEnabledRecord->enabled = false; $existingEnabledRecord->save(); } } protected function ensureAtLeastOneEnabled(int $companyId, Model $model, bool &$enabled, ?string $uniqueField = null, ?string $uniqueFieldValue = null): void { $query = $model::query()->where('company_id', $companyId) ->where('enabled', true); if ($uniqueField && $uniqueFieldValue) { $query->where($uniqueField, $uniqueFieldValue); } $otherEnabledRecord = $query->first(); if ($otherEnabledRecord === null) { $enabled = true; } } }