Laravel Notification类添加自定义方法后调用无返回值问题求助
解决Laravel自定义通知类方法调用无返回值的问题
这问题我之前排查过好几次,核心原因其实很直白:当你从$user->notifications取出数据时,Eloquent默认返回的是Illuminate\Notifications\DatabaseNotification实例,而不是你自定义的WelcomeNotification类。虽然数据库里存了你的通知类全名,但Laravel不会自动帮你把基础通知实例转换成自定义类,所以你调用myFunction()时,相当于在一个根本没有这个方法的类上调用,自然拿不到返回值。
下面给你两种可行的解决方案:
方案一:自定义通知模型(推荐)
通过重写数据库通知模型,让它支持自动解析成你的自定义通知类:
- 创建自定义通知模型
use Illuminate\Notifications\DatabaseNotification; class CustomDatabaseNotification extends DatabaseNotification { // 新增一个属性访问器,直接返回自定义通知实例 public function getNotificationAttribute() { // 从payload里取出自定义通知的类名 $notificationClass = $this->payload['type']; // 实例化自定义通知,并关联必要的属性 return app($notificationClass) ->setNotifiable($this->notifiable) ->setDatabaseNotification($this); } }
- 在User模型里指定使用这个自定义模型
修改User类里的notifications关联方法:
public function notifications() { return $this->morphMany(CustomDatabaseNotification::class, 'notifiable'); }
- 调用自定义方法
现在你可以通过notification属性拿到自定义实例,再调用方法:
$user->notifications->first()->notification->myFunction();
方案二:手动转换实例(快速临时方案)
如果不想改模型,也可以在查询后手动转换每个通知实例:
$notifications = $user->notifications->map(function ($dbNotification) { $class = $dbNotification->payload['type']; return app($class) ->setNotifiable($dbNotification->notifiable) ->setDatabaseNotification($dbNotification); }); // 现在调用方法就正常了 $notifications->first()->myFunction();
注意事项
- 确保数据库
notifications表的payload字段里,type值是你的自定义通知类的完整命名空间(比如App\Notifications\WelcomeNotification),拼写不能错; - 如果你的自定义通知类里有无法序列化的属性(比如闭包),队列处理时可能会出问题,要避免这种情况。
内容的提问来源于stack exchange,提问作者Igor Ostapiuk
相关产品推荐
相关产品推荐

