where('SiteID', $detail['SiteID']) ->where('ContactID', $contactId) ->first(); if ($existing) { $this->update($existing[$this->primaryKey], $detail); $kept[] = $existing[$this->primaryKey]; } else { $newId = $this->insert($detail); $kept[] = $newId; } } if (!empty($kept)) { $this->where('ContactID', $contactId) ->whereNotIn($this->primaryKey, $kept) ->delete(); } else { $this->where('ContactID', $contactId)->delete(); } } }