Home > Article > PHP Framework > Share Laravel7 message notification date serialization solution
→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
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 ?: 'Y-m-d H:i:s'); } }
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, 'notifiable')->orderBy('created_at', 'desc'); } }
The problem is solved, the effect is as follows:
"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!