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.
相关产品推荐
相关产品推荐

