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

Laravel使用JsonResource时serializeDate未被调用的问题排查

Laravel 10.10.1中JsonResource未触发模型serializeDate方法的问题

在Laravel 10.10.1版本中,使用JsonResource时,模型的serializeDate方法未被调用,但官方文档明确说明该方法会在序列化时触发。不过直接调用$model->toArray()等序列化操作时,该方法能正常执行。

相关代码

Model.php

protected $casts = [
    'received_at' => 'datetime:d-m-Y H:i'
];

protected function serializeDate(DateTimeInterface $date): string
{
    return $date->format('d-m-Y H:i');
}

ReadController.php

public function __invoke(ReadRequest $request, Model $model): Resource
{
    return new Resource($model);
}

Resource.php

class Resource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'received_at' => $this->received_at,
        ];
    }
}

实际返回结果

received_at: "2023-07-22T09:46:00.000000Z"

预期结果

received_at: "22-07-2023 09:46"

请问我哪里操作有误?

注意:以下方式能正常得到预期结果,但我不想使用这些方式,希望按ReadController.php中的写法实现,是否可行?

  • new Resource($report)(通过dd()打印)
  • response($report->toJson())
  • response($report->toArray())
  • response($report)

内容的提问来源于stack exchange,提问作者Kristjan O.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:52:57