diff --git a/app/Jobs/SendCampaignEmailJob.php b/app/Jobs/SendCampaignEmailJob.php index 4167206..4774b20 100644 --- a/app/Jobs/SendCampaignEmailJob.php +++ b/app/Jobs/SendCampaignEmailJob.php @@ -18,14 +18,14 @@ class SendCampaignEmailJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; - public CampaignRecipient $recipient; + public int $recipientId; /** * Create a new job instance. */ - public function __construct(CampaignRecipient $recipient) + public function __construct(int $recipientId) { - $this->recipient = $recipient; + $this->recipientId = $recipientId; } /** @@ -33,9 +33,16 @@ public function __construct(CampaignRecipient $recipient) */ public function handle(): void { - $recipient = $this->recipient; - $campaign = $this->recipient->campaign; - $contact = $this->recipient->contact; + $recipient = CampaignRecipient::query() + ->with(['campaign', 'contact']) + ->find($this->recipientId); + + if (! $recipient) { + return; + } + + $campaign = $recipient->campaign; + $contact = $recipient->contact; try { Mail::to($contact->email)->send( diff --git a/app/Services/CampaignService.php b/app/Services/CampaignService.php index 04aa92b..d1644fb 100644 --- a/app/Services/CampaignService.php +++ b/app/Services/CampaignService.php @@ -33,10 +33,15 @@ class CampaignService */ public function send(Campaign $campaign): void { - foreach ($campaign->recipients as $recipient) { - SendCampaignEmailJob::dispatch( - recipient: $recipient, - ); - } + $campaign + ->recipients() + ->select('id') + ->chunkById(100, function ($recipients): void { + foreach ($recipients as $recipient) { + SendCampaignEmailJob::dispatch( + recipientId: $recipient->id, + ); + } + }); } }