站内信发不出去主因是notifications表未建、Notifiable trait未绑定或队列未运行;DatabaseChannel仅支持基础类型数组序列化;未读统计需避免N+1并注意read_at字段精度;扩展应通过通知类而非修改核心逻辑。
站内信发不出去,90% 是因为 notifications 表没建、Notifiable trait 没绑定,或队列没跑起来。Laravel 的 Notification::send() 默认走队列,但开发环境常漏配——页面不报错,数据库里 notifications 表空空如也,用户收不到任何提示。
php artisan notifications:table 生成迁移,再 php artisan migrate
User)声明了 use Notifiable;,且类定义里写了 use Notifiable;
.env 中设 QUEUE_CONNECTION=sync
redis 或 database 驱动,并常驻运行 php artisan queue:work
implements ShouldQueue,除非你明确要强制进队列——它会绕过 QUEUE_CONNECTION=sync
DatabaseChannel 只接受纯数组,且只序列化基础类型(string/int/bool/array)。返回对象、Eloquent 模型或未重写 toArray() 的封装类,会导致 data 字段存成空或 JSON 错误。
return ['title' => '新回复', 'body' => $this->reply->content, 'link' => '/topics/123'];
return new NotificationData(...) 或 return $this->reply->toArray();(除非你确认该模型 toArray() 只返回基础类型)data 字段是 JSON 类型,MySQL 5.7+ 没问题;低版本建议把字段类型设为 longtext,防截断from_user_id)必须手动塞进返回数组,DatabaseChannel 不自动提取模型关系直接调 $user->unreadNotifications->count() 看似简单,但在列表页循环多个用户时,就是 N+1 查询。更隐蔽的是 markAsRead() 依赖 read_at 字段,而 MySQL 旧版本对 datetime(6) 微秒精度支持不稳定,导致已读状态不生效。
DB::table('notifications')->where('notifiable_id', auth()->id())->whereNull('read_at')->count()
$notification->markAsRead(),而非手动更新 read_at;若批量操作,用 Notification::markAsRead($notifications)
read_at 字段默认允许 NULL,判断未读必须用 whereNull('read_at'),不是 where('read_at', null)
notification_count 字段并配合观察者更新,别每次都 COUNT站内信不只是“一条记录”,比如要区分消息类型(评论、关注、系统公告)、支持多接收者、带附件或跳转参数。这些都不该动 notifications 表结构或重写 DatabaseChannel,而是靠通知类本身控制。
via() 中动态决定渠道:return $notifiable->prefers_sms ? ['nexmo'] : ['database'];
$type 参数,在 toDatabase() 中分支返回不同字段$sender,然后存进 data 数组,前端按需展示via() 返回空数组即可跳过该渠道,不用删类或注释方法真正难的不是写几行 notify(),而是让 data 字段可维护、查询不拖垮 DB、读写状态不丢帧——这些细节不盯住,上线后才最费时间。