db); Invoice::with([ 'invitations', 'invitations.contact.client.country', 'invitations.invoice.client.country', 'invitations.invoice.company' ]) ->withTrashed() ->whereIn('id', $this->invoice_ids) ->cursor() ->each(function ($invoice) { $invoice->service()->markSent()->save(); $invoice->invitations->each(function ($invitation) { $template = $this->resolveTemplateString($this->reminder_template); if ($invitation->contact->email && !$invitation->contact->is_locked) { $this->contact_has_email = true; $mo = new EmailObject(); $mo->entity_id = $invitation->invoice_id; $mo->template = $template; //full template name in use $mo->email_template_body = $template; $mo->email_template_subject = str_replace("template", "subject", $template); $mo->entity_class = get_class($invitation->invoice); $mo->invitation_id = $invitation->id; $mo->client_id = $invitation->contact->client_id ?? null; $mo->vendor_id = $invitation->contact->vendor_id ?? null; Email::dispatch($mo, $invitation->company->withoutRelations()); sleep(1); // this is needed to slow down the amount of data that is pushed into cache } }); if ($invoice->invitations->count() >= 1 && $this->contact_has_email) { $invoice->entityEmailEvent($invoice->invitations->first(), 'invoice', $this->reminder_template); $invoice->sendEvent(Webhook::EVENT_SENT_INVOICE, "client"); } sleep(1); // this is needed to slow down the amount of data that is pushed into cache $this->contact_has_email = false; }); } private function resolveTemplateString(string $template): string { return match ($template) { 'reminder1' => 'email_template_reminder1', 'reminder2' => 'email_template_reminder2', 'reminder3' => 'email_template_reminder3', 'endless_reminder' => 'email_template_reminder_endless', 'custom1' => 'email_template_custom1', 'custom2' => 'email_template_custom2', 'custom3' => 'email_template_custom3', default => "email_template_{$template}", }; } }