如何向Laravel Notification Facade传入集合以批量发送邮件
如何使用Laravel Notification Facade向用户集合发送邮件通知?
嘿,这事儿其实超简单的!Laravel的Notification Facade本身就支持直接传入用户集合来批量发送通知,我给你一步步拆解:
第一步:创建邮件通知类
首先你得有一个对应的通知类,用来定义邮件的内容和发送渠道。可以用Artisan命令快速生成:
php artisan make:notification SendUserEmail
生成后,打开app/Notifications/SendUserEmail.php,修改成你需要的邮件配置:
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; class SendUserEmail extends Notification { use Queueable; // 如果你需要传递动态数据,可以在这里定义属性并通过构造函数注入 // private $customMessage; // public function __construct($customMessage) // { // $this->customMessage = $customMessage; // } /** * 指定通知的发送渠道 */ public function via(object $notifiable): array { return ['mail']; // 这里指定用邮件渠道发送 } /** * 构建邮件内容 */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->subject('来自系统的专属通知') ->greeting('嗨,'.$notifiable->name.'!') ->line('这是一条为你准备的测试通知内容。') ->action('点击查看详情', url('/')) ->line('感谢你的使用!'); } }
第二步:用Notification Facade批量发送
现在直接调用Notification::send()方法,第一个参数传你的用户集合,第二个参数传刚才创建的通知类实例就行:
use App\Notifications\SendUserEmail; use Illuminate\Support\Facades\Notification; // 你的用户集合 $users = collect([ (object) [ 'name' => 'user1', 'email' => 'user1@gmail.com' ], (object) [ 'name' => 'user2', 'email' => 'user2@gmail.com' ] ]); // 批量发送通知 Notification::send($users, new SendUserEmail());
额外小提示
- 你的用户是匿名对象,Laravel会自动读取对象的
email属性作为收件人地址,刚好你的集合里已经包含这个字段,所以不用额外配置。 - 如果是Eloquent模型用户,只要模型引入了
Illuminate\Notifications\Notifiabletrait(Laravel默认的User模型已经自带),用法完全一致。 - 要是需要自定义收件人字段,可以给匿名对象添加
routeNotificationForMail()方法,比如:
$users = collect([ (object) [ 'name' => 'user1', 'email' => 'user1@gmail.com', 'routeNotificationForMail' => function () { return $this->email; // 这里可以返回任意你想用的邮箱字段 } ], // 第二个用户同理配置 ]);
内容的提问来源于stack exchange,提问作者Amir Ali
相关产品推荐
相关产品推荐

