Laravel更新函数抛出异常

时间:2018-03-29 20:09:03

标签: php laravel laravel-5

我目前正在与laravel合作并希望更新“模型”#39;用控制器

public function update(Request $request, $id)
{
    $request->validate([
        'criminal' => 'required|string',
        'crimes' => 'required|string',
        'happened_at' => 'required',
        'description' => 'required|string',
        'report' => 'string|nullable',
        'happened_at' => 'required',
        'testifies' => 'string|nullable',
        'officers' => 'string|nullable',
    ]);

    $case               = Cases::find($id);
    $case->criminal     = $request->input('criminal');
    $case->crimes       = $request->input('crimes');
    $case->officers     = $request->input('officers');
    $case->testifies    = $request->input('testifies');
    $case->report       = $request->input('report');
    $case->happened_at  = $request->input('happened_at');
    $case->crime_desc   = $request->input('description');

    $case->save();
    return redirect('cases.index');
}

它不会保存数据并引发异常:Unexpected data found. Unexpected data found. Data missing

有人知道它抛出异常的原因吗? 提前谢谢

2 个答案:

答案 0 :(得分:0)

$ case-> happen_at = $ request-> input('happen_at');可能是数据库中的日期字段 - 表格中的数据格式是否正确?

为此设置mutator:

public function setHappenedAtAttribute($value)
{
    $this->attributes['happened_at'] = Carbon\Carbon::createFromFormat('d-m-Y h:i', $value);
}

或没有碳:

public function setHappenedAtAttribute($value)
{
    $this->attributes['happened_at'] = date("d-m-Y H:i:s", strtotime($value));
}

最终位于模型的顶端:

protected $dates = [
    'created_at',
    'updated_at',
    'deleted_at',
    'happened_at'
];

答案 1 :(得分:0)

您的问题出在请求中。您的字段具有Y-m-d格式,而在碳定位器中,您的行为就好像格式为(' Y-m-d H:i:s')

我不太确定代码是否经过了mutator(从未使用过save)

This code should work:

$case               = Cases::find($id);
$case->criminal     = $request->input('criminal');
$case->crimes       = $request->input('crimes');
$case->officers     = $request->input('officers');
$case->testifies    = $request->input('testifies');
$case->report       = $request->input('report');
$case->happened_at  = Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $request->happened_at. ' 00:00:01');
$case->crime_desc   = $request->input('description');

在这种特殊情况下,我建议你实际上将happen_at作为日期而不是时间戳

如果您在模型中使用fillable,则此代码也可以正常工作

$request['happened_at'] = Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $request->happened_at. ' 00:00:01');

Cases::find($id)->update($request->all());

如果您对时区有疑虑,请以UTC格式保存所有内容,然后利用unix时间戳

Carbon\Carbon::createFromFormatUTC('Y-m-d H:i:s', $request->happened_at. ' 00:00:01');