Laravel系统通知核心是Notification类配合渠道,支持mail、database、broadcast等原生渠道及Twilio/Slack等扩展;需使用Notifiable trait,通过notify()发送,via()声明渠道,toXxx()定义格式,并优化notifications表索引。

在 Laravel 中发送系统通知,核心是使用 Notification 类配合预定义或自定义的 通知渠道(Channels)。Laravel 原生支持 mail、database、broadcast、sms(需扩展)、slack 等渠道,你可以按需选择并轻松切换。
基础通知类与发送方式
先用 Artisan 命令生成一个通知类:
php artisan make:notification UserWelcomeNotification生成的类位于 app/Notifications 目录下,默认包含 toMail() 方法。发送时直接调用用户或可通知对象的 notify() 方法:
$user->notify(new UserWelcomeNotification());注意:接收方模型需使用 Notifiable trait。
多渠道通知配置示例
一个通知可同时推送到多个渠道,只需在通知类中定义对应方法:
-
toMail($notifiable):返回
Mailable对象,用于邮件通知 -
toDatabase($notifiable):返回数组,存入
notifications表供前端拉取 - toBroadcast($notifiable):返回广播数据,配合 Laravel Echo 实现实时提醒
-
via($notifiable):显式声明启用哪些渠道,例如:
return ['mail', 'database', 'broadcast'];
短信与 Slack 渠道接入
Laravel 不内置短信和 Slack 支持,但生态成熟:
-
SMS:推荐使用
laravel-notification-channels/twilio或vonage/laravel,安装后在通知类中添加toTwilio()或toVonage()方法 -
Slack:引入
laravel-notification-channels/slack,配置 webhook URL 后,实现toSlack()方法即可推送至指定频道 - 所有第三方渠道都遵循统一模式:在
via()中加入渠道名,并提供对应 toXxx() 方法
数据库通知的读取与管理
使用 database 渠道时,通知会存入 notifications 表(需运行 php artisan notifications:table && php artisan migrate):
- 标记已读:
$user->notifications()->where('id', $id)->markAsRead(); - 获取未读数:
$user->unreadNotifications->count() - 前端可通过 API 获取:
$user->notifications()->latest()->limit(10)->get() - 建议给
notifications表的notifiable_id和notifiable_type加联合索引提升查询效率
基本上就这些。通知机制灵活,关键是根据场景选对渠道、写好格式化逻辑,并注意数据库表结构和索引优化。










