通过 Traits 实现日期序列化
<?php namespace App\Traits; use DateTimeInterface; trait SerializeDate { /** * 为 array / JSON 序列化准备日期格式 * * @param \DateTimeInterface $date * @return string */ protected function serializeDate(DateTimeInterface $date) { return $date->format('Y-m-d H:i:s'); } }
可以在BaseModel中直接使用,所有的Model都会生效
<?php namespace App\Models; use App\Traits\SerializeDate; use Illuminate\Database\Eloquent\Model; /** * App\Models\BaseModel * @mixin \Illuminate\Database\Eloquent\Model */ class BaseModel extends Model { use SerializeDate; }
参考
https://learnku.com/docs/laravel/9.x/eloquent-serialization/12256#9d4f04