'whatsapp', 'instagram_url' => 'instagram', 'facebook_url' => 'facebook', ]; public function forTenant(Tenant $tenant): Tenant { return $tenant->load(['eventDates', 'socialMedia']); } /** @param array $data */ public function updateForTenant(Tenant $tenant, array $data): Tenant { return DB::transaction(function () use ($tenant, $data): Tenant { $tenant = Tenant::query()->whereKey($tenant->getKey())->lockForUpdate()->firstOrFail(); $tenant->update([ 'event_title' => $data['title'], 'event_location' => $data['location'], ]); $this->syncDates($tenant, $data['dates']); if (array_key_exists('social_media', $data)) { $this->syncSocialMedia($tenant, $data['social_media']); } else { $this->syncLegacyContact($tenant, $data['contact']); } return $tenant->load(['eventDates', 'socialMedia']); }); } /** @param array $dates */ private function syncDates(Tenant $tenant, array $dates): void { $existingDates = $tenant->eventDates()->get()->values(); foreach (array_values($dates) as $index => $date) { $attributes = [ 'date' => $date['date'], 'time_start' => $date['start_time'], 'time_end' => $date['end_time'], ]; $existingDate = $existingDates->get($index); if ($existingDate) { $existingDate->update($attributes); } else { $tenant->eventDates()->create($attributes); } } $existingDates->slice(count($dates))->each->delete(); $tenant->unsetRelation('eventDates'); } /** @param array $contact */ private function syncLegacyContact(Tenant $tenant, array $contact): void { foreach (self::CONTACT_CODES as $field => $code) { $url = $contact[$field] ?? null; if ($url === null || $url === '') { $tenant->socialMedia()->detach($code); continue; } $tenant->socialMedia()->syncWithoutDetaching([ $code => ['url' => $url], ]); } $tenant->unsetRelation('socialMedia'); } /** @param array $socialMedia */ private function syncSocialMedia(Tenant $tenant, array $socialMedia): void { $associations = []; foreach (array_values($socialMedia) as $index => $item) { $associations[$item['code']] = [ 'url' => $item['url'], 'orden' => $item['orden'] ?? $index, ]; } $tenant->socialMedia()->sync($associations); $tenant->unsetRelation('socialMedia'); } }