我正在尝试向一组用户发送通知。 根据 Laravel 文档,我应该能够发送通知,如下所示:
Notification::send($users, new ConsumableNotification($arguments));
只要
$users
是可通知对象的集合或数组。
但是我面临这个错误:
Symfony\Component\Mime\Exception\LogicException
An email must have a "To", "Cc", or "Bcc" header.
我尝试向个人用户发送通知如下
foreach ($users as $user) {
$user->notify(new ConsumableNotification($arguments));
}
出现同样的错误。但是明确发送邮件:
foreach ($users as $user) {
Mail::to($user)
->send(new ConsumableAlert($arguments));
}
有效,所以我认为通知类中出了问题。 通知类定义如下:
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
];
}
}
有人发现问题了吗?
花了很多时间后,我发现需要在通知类中添加
to
方法,如下所示:
/**
* 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);
}
不知何故,我在阅读文档时错过了 5 次。