How to send laravel 10 fortify reset password email via database queue system?

20 Views Asked by At

I have Laravel 10 as my API backend with Fortify. When resetting the password, I want to send HTML content (retrieved from the database) to an email. The email should be queued, possibly via the jobs table.

In FortifyServiceProvider, I have tried the toMailUsing method.

ResetPassword::toMailUsing(function (User $user, string $token) {
    return (new ResetEmail($user, $token))->onQueue('send-email');
});

But this email needs to be queued and sent directly.

FYI: I am already running send-email queue to send other emails, and it is working perfectly fine (via Jobs). And yes, I do have set this in .env QUEUE_CONNECTION=database

In laravel source i have found this:

if ($message instanceof Mailable) {
    return $message->send($this->mailer);
}

This is supposed to handle the queued Mailable as well, right? Or am I heading in the wrong direction?

Source:10.x/src/Illuminate/Notifications/Channels/MailChannel.php#L63

1

There are 1 best solutions below

0
Symfony TestMail On

Fixed with these changes.

  1. Created notification table with
php artisan notifications:table
 
php artisan migrate
  1. Created custom notification class
<?php

namespace App\Notifications;

use App\Models\User;
use App\Mail\ResetEmail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;

class ResetEmailNotificationQueued extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     */
    public function __construct(private string $token)
    {
        $this->onQueue('send-email');
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    /**
     * 
     * @param User $notifiable
     * 
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): Mailable
    {
        return new ResetEmail($notifiable, $this->token);
    }
}

  1. Updated Models\User.php
public function sendPasswordResetNotification($token)
{
    $this->notify(new ResetEmailNotificationQueued($token));
}
  1. Run queue
php artisan queue:listen --queue=default,send-email

Cheers :).