I am using laravel notifications with queues. Here's my code:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use JetBrains\PhpStorm\ArrayShape;
class SendVerifyEmailOTP extends Notification implements ShouldQueue
{
use Queueable;
protected string $name, $email, $otp, $uniq_id;
/**
* Create a new notification instance.
*
* @param $name
* @param $email
* @param $otp
* @param $uniq_id
*/
public function __construct($name, $email, $otp, $uniq_id)
{
$this->name = $name;
$this->email = $email;
$this->otp = $otp;
$this->uniq_id = $uniq_id;
}
/**
* Get the notification's delivery channels.
*
* @return array
*/
public function via(): array
{
return ['mail', 'database'];
}
/**
* Get the mail representation of the notification.
*
* @return MailMessage
*/
public function toMail(): MailMessage
{
return (new MailMessage)
->subject('Verification Email')
->greeting('Hello ' . $this->name)
->line('GrayScale is one of the fastest growing peer to peer (P2P) lending platforms in Bangladesh. It connects investors or lenders looking
for high returns with creditworthy borrowers looking for short term
personal loans.')
->line('Your One Time Password (OTP) is ' . $this->otp)
->action('Verify Your Email', url('/api/verify-email/' . $this->email . '/' . $this->uniq_id));
}
# Saving data to the database
#[ArrayShape(['msg' => "string"])] public function toDatabase(): array
{
return [
'msg' => 'Verification Email Sent. Check Inbox'
];
}
/**
* Get the array representation of the notification.
*
* @return array
*/
public function toArray(): array
{
return [
//
];
}
}
And I am calling it like this...
Notification::route('mail', [$email => $user->name])
->notify(new SendVerifyEmailOTP($user->name, $email, $otp, $uniq_id));
The problem here is the job executes twice. It evens has two entries in the jobs table in the database. What am I doing wrong here? Do I really need to create jobs separately for every notification if I want to use queues? I mean it's working but it's just executing twice.
It is because you have two channels (see the via
method) on your notification class. Assuming you're using the database
connection (check your .env
for the value of QUEUE_CONNECTION) for queueing, you just need to have mail
as your channel.