I am using Laravel Mailable to send email, and I want to log the email that was successfully sent.
Laravel Mailable have default event that was fired after the email was sent
https://laravel.com/docs/5.6/mail#events
So I hook my listener to this event
protected $listen = [
'App\Events\Event' => [
'App\Listeners\EventListener',
],
'Illuminate\Mail\Events\MessageSent' => [
'App\Listeners\LogSentEmailNotification',
],
];
Listener handler
public function handle(MessageSent $event)
{
//get extra data
$job_request_id = $event->message->job_request_id;
$message = $event->message;
$data = [
'job_request_id' => $job_request_id,
'to' => $message->getHeaders()->get('To'),
'from' => $message->getHeaders()->get('From'),
'cc' => $message->getHeaders()->get('Cc'),
'bcc' => $message->getHeaders()->get('Bcc'),
'subject' => $message->getHeaders()->get('Subject')->getFieldBody(),
'body' => $message->getBody(),
];
$email_notification_log = $this->email_notification_log->create($data);
}
The extra data job_request_id is passed from the build() method in Mailable class, CustomEmailNotification.php
class CustomEmailNotification extends Mailable implements ShouldQueue
{
public function build()
{
$job_request_id = 1;
//pass extra data mail message
$this->withSwiftMessage(function ($message) use($job_request_id){
$message->job_request_id = $job_request_id;
});
}
}
Right now this line on Listener class is working fine without queue, however when using queue it will return null
//get extra data
$job_request_id = $event->message->job_request_id;
var_dump($job_request_id);
//null when using queue
Question is, what is the correct way to pass custom data to MailSent event when using queue?
Or is there possibility job_request_id is lost when using queue and pass to withSwiftMessage(), so the Event Listener just received null value?
Thanks