→推荐:《laravel教程

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

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 消息通知日期序列化解决方案 《相关推荐:最新的五个Laravel视频教程

以上就是分享Laravel7消息通知日期序列化解决方案的详细内容,更多请关注亿码酷站其它相关文章!



分享Laravel7消息通知日期序列化解决方案
—–文章转载自PHP中文网如有侵权请联系ymkuzhan@126.com删除

下载声明:
  • 本站资源如无特殊说明默认解压密码为www.ymkuzhan.com建议使用WinRAR解压;
  • 本站资源来源于用户分享、互换、购买以及网络收集等渠道,本站不提供任何技术服务及有偿服务,资源仅提供给大家学习研究请勿作它用。
  • 赞助本站仅为维持服务器日常运行并非购买程序及源码费用因此不提供任何技术支持,如果你喜欢该程序,请购买正版!
  • 版权声明:
  • 下载本站资源学习研究的默认同意本站【版权声明】若本站提供的资源侵犯到你的权益,请提交版权证明文件至邮箱ymkuzhan#126.com(将#替换为@)站长将会在三个工作日内为您删除。
  • 免责声明:
  • 您好,本站所有资源(包括但不限于:源码、素材、工具、字体、图像、模板等)均为用户分享、互换、购买以及网络收集而来,并未取得原始权利人授权,因此禁止一切商用行为,仅可用于个人研究学习使用。请务必于下载后24小时内彻底删除,一切因下载人使用所引起的法律相关责任,包括但不限于:侵权,索赔,法律责任,刑事责任等相关责任,全部由下载人/使用人,全部承担。以上说明,一经发布视为您已全部阅读,理解、同意以上内容,如对以上内容持有异议,请勿下载,谢谢配合!支持正版,人人有责,如不慎对您的合法权益构成侵犯,请联系我们对相应内容进行删除,谢谢!