client->contacts; $contacts->each(function ($contact) use($invoice){ $invitation = InvoiceInvitation::whereCompanyId($invoice->company_id) ->whereClientContactId($contact->id) ->whereInvoiceId($invoice->id) ->first(); if (!$invitation && $contact->send_invoice) { $ii = InvoiceInvitationFactory::create($invoice->company_id, $invoice->user_id); $ii->invoice_id = $invoice->id; $ii->client_contact_id = $contact->id; $ii->save(); } elseif ($invitation && !$contact->send_invoice) { $invitation->delete(); } }); return $invoice; } }