I am trying to send a notification to a set of users. According to the Laravel documentation I should be able to send notifications as follows:
Notification::send($users, new ConsumableNotification($arguments));
as long as the $users
is a collection or array of notifiable objects.
However I am facing this error:
Symfony\Component\Mime\Exception\LogicException
An email must have a "To", "Cc", or "Bcc" header.
I have tried sending notifications to the individual users as follows
foreach ($users as $user) {
$user->notify(new ConsumableNotification($arguments));
}
With the same error occurring. However sending a mail explicitly:
foreach ($users as $user) {
Mail::to($user)
->send(new ConsumableAlert($arguments));
}
works, so I assume something goes wrong in the notification class. The notification class is defined as follows:
class ConsumableNotification extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct(
public ConsumableTypes $consumableType,
public float|null $remains = null,
public Carbon|null $expires = null,
)
{
//
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail', 'database'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new ConsumableAlert(
$this->consumableType,
$this->remains,
$this->expires
));
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
'consumable_type_id' => $this->consumableType->id,
'remains' => $this->remains,
'expires' => $this->expires
];
}
}
Does anyone spot the issue?
After spending way to much time I saw that one is required to add the to
method in the notification class like this:
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Mail\Mailable
*/
public function toMail($notifiable)
{
return (new MyMailable($arguments))
->to($notifiable->email);
}
Somehow I missed it 5 times when reading the documentation.