You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8升级后serializeDate()报错:DateTimeInterface参数为null

解决Laravel升级后serializeDate()的TypeError问题

问题根源

错误提示Argument 1 passed to App\Models\User::serializeDate() must implement interface DateTimeInterface, null given,本质是当created_at或updated_at字段为null时,直接调用要求接收DateTimeInterface类型参数的serializeDate方法,导致类型不匹配。

解决方案

方案1:修改模型的serializeDate方法,兼容null值

直接修改模型中的serializeDate方法,允许参数为null,并返回对应结果:

/**
 * Prepare a date for array / JSON serialization.
 *
 * @param  \DateTimeInterface|null  $date
 * @return string|null
 */
public function serializeDate(?DateTimeInterface $date)
{
    return $date?->format('Y-m-d H:i:s');
}

这里使用PHP空安全运算符?->,当$date为null时直接返回null,避免触发类型错误。

方案2:在资源中先判断字段是否为null再调用方法

如果不想修改模型方法,可在UserResource中添加null判断逻辑:

public function toArray($request)
{
    return [
        'slack'            => $this->slack,
        'user_code'        => $this->user_code,
        'created_at_label' => $this->created_at ? $this->serializeDate($this->created_at) : null,
        'updated_at_label' => $this->updated_at ? $this->serializeDate($this->updated_at) : null,
        'created_by'       => $this->createdUser,
        'updated_by'       => $this->updatedUser
    ];
}

额外优化建议

Laravel框架原本的serializeDate方法是在模型序列化时自动处理日期字段的,通常无需手动在资源中调用。如果你的需求是统一日期格式,可直接修改模型的$dateFormat属性实现,无需自定义serializeDate:

protected $dateFormat = 'Y-m-d H:i:s';

这样框架会自动按指定格式序列化日期字段,既简化代码也能避免null值的问题。

内容的提问来源于stack exchange,提问作者Abdullah Hamada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 18:37:34