→推荐:《laravel教程》
由于项目中使用到了消息通知功能,于是自然而然写出了如下代码
public function index(Request $request) { $notifications = \Auth::user()->notifications()->paginate($request->size); return $this->success($notifications); }
然而发现日期格式化不对
但是模型基类使用了 HasDateTimeFormatter trait, 代码如下:
<?php namespace App\Models\Traits; trait HasDateTimeFormatter { protected function serializeDate(\DateTimeInterface $date) { return $date->format($this->dateFormat ?: 'Y-m-d H:i:s'); } }
查看源代码发现 Illuminate\Notifications\Notifiable 这个 trait 有两个 trait,其中
Illuminate\Notifications\HasDatabaseNotifications 的 notifications() 方法关联的是Illuminate\Notifications\DatabaseNotification 这个类, 由于这个类是laravel 自带的, 所以serializeDate方法自然不会起作用。
找到了问题所在,那就解决吧。首先定义自己的 Notification 模型类, 继承自框架自带的 Illuminate\Notifications\DatabaseNotification 类,再引用 HasDateTimeFormatter trait,代码如下:
<?php namespace App\Models; use App\Models\Traits\HasDateTimeFormatter; use Illuminate\Notifications\DatabaseNotification; class Notification extends DatabaseNotification { use HasDateTimeFormatter; public function notifiable() { return $this->morphTo(); } }
最后我们在 User 模型中覆盖 notifications() 方法,使用我们自己定义的 Notification 模型来关联,代码如下:
<?php namespace App\Models; use App\Models\Traits\HasDateTimeFormatter; use Illuminate\Foundation\Auth\User as Authenticatable; use Tymon\JWTAuth\Contracts\JWTSubject; class User extends Authenticatable implements JWTSubject { use Notifiable, HasDateTimeFormatter; public function notifications() { return $this->morphMany(Notification::class, 'notifiable')->orderBy('created_at', 'desc'); } }
问题解决,效果如下:
《相关推荐:最新的五个Laravel视频教程》
以上就是分享Laravel7消息通知日期序列化解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号