How to check mail is send successfully or not and save status in laravel notification?

3.5k Views Asked by At

I'm using laravel notifications for sending email and save to database. How to check mail status after sending email and how to save it in the notification table?

public function via($notifiable)
{
    return ['mail', DbChannel::class];
}

public function toMail($notifiable)
{
    return (new MailMessage)
        ->from('[email protected]', 'Example')
        ->line('...');
}
1

There are 1 best solutions below

0
On BEST ANSWER

to handle this you can define listener and event . you first register it in App\Providers\EventServiceProvider

protected $listen = [
    'App\Events\Event' => [
        'App\Listeners\EventListener',
    ],
    'Illuminate\Mail\Events\MessageSending' => [
        'App\Listeners\LogSendingMessage',
    ],
    'Illuminate\Mail\Events\MessageSent' => [
        'App\Listeners\LogSentMessage',
    ],
];

and then in App\Listeners\LogSendingMessage ,save send status. for example

   public function handle(MessageSending $event)
{
    $notification = Notification::where('id',$event->data['notification']->id)->first();
    $notification->status = "Sending";
    $notification->save();
}

public function failed(MessageSending $event, $exception)
{
    $notification = Notification::where('id',$event->data['notification']->id)->first();
    $notification->status = "Sending Event Failed";
    $notification->save();
}

also for LogSentMessage.... See this link for more information https://laravel.com/docs/8.x/mail#events