【问题标题】:Laravel Carbon error data missing with casting铸造时缺少 Laravel Carbon 错误数据
【发布时间】:2019-11-18 08:27:54
【问题描述】:

我有一个日期属性,我尝试在保存期间将其转换为 DateTime 格式。

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

在我的控制器中,我有以下方法。

public function change(int $gameSerieId, Request $request)
{
    try {
        $gameSerie = GameSerie::findOrFail($gameSerieId);
        $gameSerie->update($request->all());

        return response()->json('ok');
    } catch (\Exception $exception) {
        throw new GameApiException('Something went wrong!');
    }
}

但是,我收到“数据丢失”错误,因为我的日期输入格式看起来像一个字符串:2019-11-17 21:00

【问题讨论】:

    标签: laravel-6


    【解决方案1】:

    我发现了使用 mutators 设置属性的能力

    public function setDateAttribute($date)
    {
        $this->attributes['date'] = Carbon::make($date);
    }
    

    https://laravel.com/docs/5.7/eloquent-mutators#defining-a-mutator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 2017-12-11
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 2013-06-11
      相关资源
      最近更新 更多