laravel通知本身不记录渠道和状态,需通过via()方法确定发送渠道,并结合数据库表、日志、队列失败表或自定义通知日志表追踪状态。

在 Laravel 中,自定义通知(Notification)本身不直接记录发送渠道和状态,它只是一个“消息定义”。真正决定发往哪、是否成功、失败原因等信息,取决于你使用的 通知驱动(如 database、mail、broadcast、nexmo、slack 等)以及是否启用了 通知日志 或 队列监听。要查看渠道与状态,关键在于「如何投递」和「投递后如何追踪」。
1. 查看通知实际使用的发送渠道
通知类中的 via() 方法决定了该通知会尝试通过哪些渠道发送。它接收一个可通知实体(如 User),返回数组:
public function via($notifiable)
{
return ['database', 'mail']; // 会同时发到数据库和邮箱
}
但最终是否真走某个渠道,还受以下影响:
-
可通知实体是否实现了对应渠道的接收方法:比如
routeNotificationForMail()返回 null,则不会发邮件;未定义routeNotificationForDatabase()则无法存入notifications表。 -
环境或配置开关:例如开发环境禁用邮件(
MAIL_MAILER=smtp未配或设为log),则mail渠道看似启用,实则只写日志不发信。 -
条件逻辑:你可以在
via()中动态判断:return $notifiable->prefers_sms ? ['nexmo'] : ['database'];
2. 查看通知是否已发送成功(状态追踪)
Laravel 默认不自动记录通知“发送成功/失败”状态,需手动介入。常见方式如下:
-
Database 驱动 → 查
notifications表:只要via()包含database,且实体支持,Laravel 就会把通知序列化后存入该表。字段read_at为空表示未读,非空表示已读 —— 这是唯一由框架自动维护的“状态”。但它不反映“是否发出去了”,只代表“是否被查收”。 -
Mail 驱动 → 查日志或使用 MailTrap / SMTP 日志:开启
MAIL_LOG_LEVEL=debug并配合storage/logs/laravel.log,可看到类似[2024-05-20 10:22:33] local.DEBUG: Sending mail to user@example.com的记录。若用 Mailtrap,登录后台即可确认是否收到。 -
队列驱动 → 查
failed_jobs表或 Horizon:如果通知通过队列异步发送(加了ShouldQueue),失败会进failed_jobs;成功则无显式记录。建议搭配 Laravel Horizon 或自定义failed()方法捕获异常并落库。 -
自定义日志 + 事件监听:监听
Illuminate\Notifications\Events\NotificationSent和NotificationFailed事件,在EventServiceProvider中注册,记录渠道、用户 ID、时间、错误信息等。
3. 快速调试:临时强制指定渠道并打印日志
开发时想立刻知道某次通知走了哪个渠道,可在发送前加调试代码:
$user = User::find(1);
$notification = new InvoicePaid($invoice);
// 手动调用 via() 查看结果
$channels = $notification->via($user);
Log::info('Notification channels:', ['channels' => $channels, 'user_id' => $user->id]);
// 强制只走 database 调试
$user->notify(new class extends Notification {
public function via($notifiable) { return ['database']; }
public function toDatabase($notifiable) { return ['message' => 'Debug only']; }
});
4. 推荐方案:构建轻量通知状态表(production 可用)
如需长期追踪每条通知的渠道、状态、时间、错误,建议新建一张表(如 notification_logs):
Schema::create('notification_logs', function (Blueprint $table) {
$table->id();
$table->string('notifiable_type');
$table->unsignedBigInteger('notifiable_id');
$table->string('notification_class'); // App\Notifications\InvoicePaid
$table->string('channel'); // database, mail, slack
$table->enum('status', ['sent', 'failed', 'queued']);
$table->text('error')->nullable();
$table->timestamps();
});
然后在通知类的 toMail()、toDatabase() 等方法中,或通过事件监听器插入日志。这样就能按用户、渠道、时间维度查询发送情况。











