Laravel 7 消息通知日期序列化解决方案

由于项目中使用到了消息通知功能,于是自然而然写出了如下代码

public function index(Request $request)
{
    $notifications = \Auth::user()->notifications()->paginate($request->size);

    return $this->success($notifications);
}

然而发现日期格式化不对

Laravel 7 消息通知日期序列化解决方案

但是模型基类使用了 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\HasDatabaseNotificationsnotifications() 方法关联的是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 7 消息通知日期序列化解决方案

本作品采用《CC 协议》,转载必须注明作者和本文链接
为了点个赞,专门注册的账号
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!