laravel通知系统专为异步、多通道(邮件/短信/数据库/slack等)用户级消息设计,不处理前端提示;需通过notification::send()或notifiable模型的notify()触发,且接收者必须实现notifiable trait。

Laravel 的通知系统不是用来发“弹窗提示”或前端 toast 的,而是专为异步、多通道(邮件、短信、数据库记录、Slack 等)的用户级消息设计的。它不负责前端展示逻辑,也不替代 session()->flash() 这类瞬时状态提示。
怎么创建一个可发送的通知类
用 Artisan 命令生成通知类是最稳妥的方式,它会自动放在 app/Notifications 目录下,并实现 ShouldQueue 接口(默认支持队列):
php artisan make:notification OrderShipped
生成的类里,toMail() 方法决定邮件内容,toDatabase() 决定存进数据库的结构,via() 控制启用哪些渠道。别手动 new 通知类再调用 send() —— Laravel 要求你用 Notification::send() 或模型上的 notify() 方法触发。
-
via()返回数组,比如['mail', 'database'];如果返回空数组,通知会被静默丢弃 - 数据库通知需要先运行
php artisan notifications:table && php artisan migrate - 邮件通知依赖已配置好的 Mailer,没配好会抛出
Symfony\Component\Mailer\Exception\TransportException
通知发给谁:$notifiable 对象必须实现 Notifiable trait
只有实现了 Notifiable trait 的模型(如 User)才能接收通知。这个 trait 提供了 notify() 方法和 routesNotifications() 的默认行为。
如果你要通知一个非 Eloquent 对象(比如临时构造的客户数据),必须手动实现 routeNotificationForMail() 和/或 routeNotificationForDatabase() 方法,否则 Notification::send() 会报错 Call to undefined method ...::routeNotificationForMail()。
- 常见错误:直接传数组或 stdClass 给
Notification::send()→ 必须是实现了Notifiable的实例 - 自定义路由方法名必须严格匹配渠道名,比如 Slack 就得叫
routeNotificationForSlack() -
notify()是实例方法,不能在静态上下文中调用
邮件通知里怎么动态传参
通知类的构造函数可以接收任意参数,Laravel 会原样传入。这些参数通常用于模板渲染或渠道逻辑判断:
class OrderShipped extends Notification<br>{<br> public $order;<br><br> public function __construct($order)<br> {<br> $this->order = $order;<br> }<br><br> public function toMail($notifiable)<br> {<br> return (new MailMessage)<br> ->line('Your order #' . $this->order->id . ' has shipped.');<br> }<br>}
注意:$this->order 在邮件发送时才被访问,所以它必须是可序列化的(Eloquent 模型默认支持)。但如果传的是 Closure、resource 或未加载关系的模型,在队列中反序列化时会失败,报 Unserialization of 'Closure' is not allowed 或 N+1 查询问题。
- 推荐做法:只传 ID,在
toMail()里重新查询,或用load()预加载必要关系 - 不要在构造函数里做 DB 查询或 API 调用 —— 违反通知类的无副作用原则
- 如果要用 Blade 模板,确保
toMail()返回的MailMessage调用了view()而不是line()
数据库通知怎么查和标记已读
数据库通知存在 notifications 表,每条记录有 read_at 字段。Laravel 提供了现成的 Eloquent 方法:
-
$user->unreadNotifications→ 获取未读通知集合(Eloquent Collection) -
$user->readNotifications→ 已读通知 -
$notification->markAsRead()→ 标记单条为已读 -
$user->markAsRead()→ 批量标记所有未读为已读
注意:unreadNotifications 是动态访问器,每次调用都查库;如果页面需多次使用,建议缓存结果。另外,notifications 表默认没有索引,高并发场景下对 notifiable_id 和 notifiable_type 加联合索引能明显提升查询速度。











