Laravel 使用资源时转换模型值

Laravel cast model values when using Resource

当使用资源 created_atupdated_at casting 返回模型时工作正常, 但是当我修改 toArray() 函数时,转换不起作用!

在我的模型中:

protected $casts = [
    'created_at' => 'datetime:Y-m-d:h',
    'updated_at' => 'datetime:Y-m-d:h',
];

在资源中:

 public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'value' => $this->value,
        'box' =>  new BoxResource($this->box),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

在控制器中:

  public function index(Request $request)
{

    return CurrencyResource::collection(
        Currency::where("user_id", "=", $request->user()->id)
          
            ->paginate($per_page)
    );
}

如何进行铸造?

它不起作用,你的意思是时间戳恢复为碳实例?那你可以只使用格式方法。

'created_at' => $this->created_at->format('Y-m-d:h'),
'updated_at' => $this->updated_at->format('Y-m-d:h'),