日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

由于項目中使用到了消息通知功能,于是自然而然寫出了如下代碼

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

然而發現日期格式化不對


60e5538b9db7e.png


但是模型基類使用了 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');
    }
}

問題解決,效果如下:


60e553fe0f4c1.png


分享到:
標簽:Laravel7 消息通知 日期序列化
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定