contacts->pluck('id')->diff($contacts->pluck('id'))->each(function ($contact) { ClientContact::destroy($contact); }); $this->is_primary = true; /* Set first record to primary - always */ $contacts = $contacts->sortByDesc('is_primary')->map(function ($contact) { $contact['is_primary'] = $this->is_primary; $this->is_primary = false; return $contact; }); //loop and update/create contacts $contacts->each(function ($contact) use ($client) { $update_contact = null; if (isset($contact['id'])) { $update_contact = ClientContact::find($contact['id']); } if (!$update_contact) { $update_contact = ClientContactFactory::create($client->company_id, $client->user_id); $update_contact->client_id = $client->id; } $update_contact->fill($contact); if (array_key_exists('password', $contact)) { if (strlen($contact['password']) == 0) { $update_contact->password = ''; } else { $update_contact->password = Hash::make($contact['password']); } } $update_contact->save(); }); //always made sure we have one blank contact to maintain state if ($client->contacts->count() == 0) { info("no contacts found"); $new_contact = ClientContactFactory::create($client->company_id, $client->user_id); $new_contact->client_id = $client->id; $new_contact->contact_key = Str::random(40); $new_contact->is_primary = true; $new_contact->save(); } } }