$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 } $data['services'] = $tenant->services ->mapWithKeys(fn (TenantService $service): array => [$service->service => [ 'is_enabled' => $service->is_enabled, 'api_key' => $service->api_key, ]]) ->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::cases() as $service) { $state = $this->services[$service->value] ?? []; $tenant->services()->updateOrCreate( ['service' => $service->value], [ 'is_enabled' => (bool) ($state['is_enabled'] ?? false), 'api_key' => filled($state['api_key'] ?? null) ? $state['api_key'] : null, ], ); } $tenant->unsetRelation('services'); } }