$data * @return array */ protected function mutateFormDataBeforeFill(array $data): array { $tenant = $this->record; if (! $tenant instanceof Tenant) { return $data; // creating: there is nothing to read yet } $stored = $tenant->services->keyBy('service'); $data['services'] = collect(TenantServiceKey::wired()) ->mapWithKeys(fn (TenantServiceKey $service): array => [$service->value => [ 'is_enabled' => $stored->get($service->value)?->is_enabled ?? $service->enabledByDefault(), ]]) ->all(); return $data; } /** * @param array $data * @return array */ protected function mutateFormDataBeforeCreate(array $data): array { return $this->withoutServices($data); } /** * @param array $data * @return array */ protected function mutateFormDataBeforeSave(array $data): array { return $this->withoutServices($data); } protected function afterCreate(): void { $this->saveServices(); } protected function afterSave(): void { $this->saveServices(); } /** * @param array $data * @return array */ private function withoutServices(array $data): array { $this->services = is_array($data['services'] ?? null) ? $data['services'] : []; unset($data['services']); return $data; } private function saveServices(): void { $tenant = $this->record; if (! $tenant instanceof Tenant) { return; } foreach (TenantServiceKey::wired() as $service) { $state = $this->services[$service->value] ?? []; $tenant->services()->updateOrCreate( ['service' => $service->value], ['is_enabled' => (bool) ($state['is_enabled'] ?? false)], ); } $tenant->unsetRelation('services'); app(TenantFeatures::class)->forget($tenant); } }