Home  >  Article  >  PHP Framework  >  Share Laravel7 message notification date serialization solution

Share Laravel7 message notification date serialization solution

藏色散人
藏色散人forward
2021-06-30 15:25:101898browse

→Recommended: "laravel tutorial"

Since the message notification function is used in the project, I naturally wrote the following code

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

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

However, it was found that the date format is incorrect

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

But the model base class uses the HasDateTimeFormatter trait, the code is as follows:

<?php

namespace App\Models\Traits;

trait HasDateTimeFormatter
{
    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: &#39;Y-m-d H:i:s&#39;);
    }
}

View source code Found that Illuminate\Notifications\Notifiable This trait has two traits, among which the
notifications() method of Illuminate\Notifications\HasDatabaseNotifications is associated with Illuminate\Notifications\DatabaseNotification This class, since this class comes with laravel, the serializeDate method will naturally not work.
If you find the problem, let’s solve it. First define your own Notification model class, inherit from the Illuminate\Notifications\DatabaseNotification class that comes with the framework, and then reference the HasDateTimeFormatter trait, the code is as follows:

<?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();
    }
}

Finally, we override the notifications() method in the User model and use our own defined Notification model to associate. The code is as follows:

<?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, &#39;notifiable&#39;)->orderBy(&#39;created_at&#39;, &#39;desc&#39;);
    }
}

The problem is solved, the effect is as follows:

Laravel 7 消息通知日期序列化解决方案 "Related recommendations: The latest five Laravel video tutorials"

The above is the detailed content of Share Laravel7 message notification date serialization solution. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete