You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel事件监听器未触发:创建收据后无法发送邮件

Laravel事件监听器未触发排查方案(收据创建后发送邮件场景)

问题背景

收据创建完成后,ReceiptCreatedEvent已触发,但对应的SendReceiptNotification监听器未执行,info()日志无输出;直接调用邮件发送功能正常,排除邮件配置问题。

排查与解决步骤

1. 确保事件监听器注册生效

Laravel会缓存事件与监听器的映射关系,修改EventServiceProvider后需更新缓存:

  • 清除旧缓存:php artisan event:clear
  • 生成新缓存:php artisan event:cache
  • 确认EventServiceProvider中$listen数组的类名、命名空间无拼写错误:
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        ReceiptCreatedEvent::class => [
            SendReceiptNotification::class,
        ],
    ];
    

2. 检查队列执行状态

你的监听器实现了ShouldQueue接口,意味着逻辑会进入异步队列执行:

  • 如果未启动队列worker,任务会堆积无法执行,启动worker:php artisan queue:work
  • 本地排查时可临时改为同步执行:移除ShouldQueue接口和InteractsWithQueue trait,监听器会在事件触发时立即执行,便于观察日志。

3. 修正日志输出逻辑

原日志直接拼接模型对象只会输出类名,无法验证数据是否正确传递:

// 原代码
info("This is the receipt: " . $event->receipt);
// 修改为
info("ReceiptCreatedListener triggered, receipt ID: " . $event->receipt->id);

4. 验证事件是否真的触发

在事件构造函数中添加日志,确认事件被正确dispatch:

// App\Events\ReceiptCreatedEvent
public function __construct(public Racun $receipt)
{
    info("ReceiptCreatedEvent triggered, receipt ID: " . $this->receipt->id);
}

5. 检查模型关联与数据完整性

确认Racun模型的user()关联定义正确,且创建收据时user_id对应用户存在:

// 在监听器中增加关联校验
if (!$event->receipt->user) {
    info("No user found for receipt ID: " . $event->receipt->id);
    return;
}

6. 简化事件构造函数(可选优化)

PHP8构造属性提升已自动赋值,无需手动重复赋值:

// 原代码
public function __construct(public Racun $receipt)
{
    $this->receipt = $receipt;
}
// 简化为
public function __construct(public Racun $receipt) {}

内容的提问来源于stack exchange,提问作者Kubura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 15:52:50