使用资源时,Laravel会强制转换模型值
当使用资源使用资源时,Laravel会强制转换模型值,laravel,laravel-resource,Laravel,Laravel Resource,当使用资源返回模型时,在处创建的和在处更新的铸造工作正常, 但是当我修改toArray()函数时,强制转换不起作用 在我的模型中: protected $casts = [ 'created_at' => 'datetime:Y-m-d:h', 'updated_at' => 'datetime:Y-m-d:h', ]; 在资源方面: public function toArray($request) { return [ 'id' =&g
返回模型时,在
处创建的和在
处更新的铸造
工作正常,
但是当我修改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'),
回答很好,但是有没有办法解决这个问题呢?使用$cast
,文档中关于日期转换的主题很清楚。“将模型序列化为数组或JSON时将使用此格式:”