Laravel中如何检查通知是否发送成功?
解决Laravel通知发送成功状态判断的问题
因为Notification::send()方法返回值是void,没法直接通过返回值调用success()方法判断状态,你可以通过以下几种方式实现需求:
方法一:捕获发送过程中的异常
Laravel在通知发送失败时(比如邮件配置错误、第三方通道调用失败等)会抛出异常,通过try-catch块捕获这些异常来判断发送状态:
public function AskForLevelUp() { try { $admin = User::where('is_admin', 1)->first(); Notification::send($admin, new LevelUpNotification(Auth::user()->id)); return back()->with('success', 'Your request has been submitted, please wait for admin confirmation.'); } catch (\Exception $e) { // 可在此记录错误日志,方便后续排查问题 \Log::error('Level up notification failed: ' . $e->getMessage()); return back()->with('failure', 'Something went wrong, your request is not submitted. Please try again later.'); } }
方法二:检查数据库通知记录(如果使用数据库通道)
如果你的通知配置了数据库存储通道(默认的database通道),可以在发送后查询数据库,确认是否生成了对应的通知记录:
public function AskForLevelUp() { $admin = User::where('is_admin', 1)->first(); $userId = Auth::user()->id; Notification::send($admin, new LevelUpNotification($userId)); // 检查admin是否收到了这条目标通知 $notificationExists = $admin->notifications() ->where('type', LevelUpNotification::class) ->where('data->user_id', $userId) // 假设通知的data字段中包含user_id ->exists(); if ($notificationExists) { return back()->with('success', 'Your request has been submitted, please wait for admin confirmation.'); } else { return back()->with('failure', 'Something went wrong, your request is not submitted. Please try again later.'); } }
方法三:自定义通道的发送状态追踪
如果你使用的是自定义通知通道(比如短信、第三方推送),可以在通知类的对应发送方法里捕获发送结果,比如在toMail()或自定义的ToXXX()方法中记录状态:
// LevelUpNotification.php class LevelUpNotification extends Notification { public $sendSuccess = false; public function __construct(public $userId) {} public function via($notifiable) { return ['mail']; // 假设使用邮件通道 } public function toMail($notifiable) { try { $message = (new MailMessage) ->line('User ' . $this->userId . ' is requesting level up.'); $this->sendSuccess = true; return $message; } catch (\Exception $e) { $this->sendSuccess = false; throw $e; // 继续抛出异常让外层捕获,或自行处理 } } }
然后在控制器中调用:
public function AskForLevelUp() { try { $admin = User::where('is_admin', 1)->first(); $notification = new LevelUpNotification(Auth::user()->id); Notification::send($admin, $notification); if ($notification->sendSuccess) { return back()->with('success', 'Your request has been submitted, please wait for admin confirmation.'); } else { return back()->with('failure', 'Something went wrong, your request is not submitted. Please try again later.'); } } catch (\Exception $e) { \Log::error('Notification failed: ' . $e->getMessage()); return back()->with('failure', 'Something went wrong, your request is not submitted. Please try again later.'); } }
内容的提问来源于stack exchange,提问作者T R A C E ツ
相关产品推荐
相关产品推荐

