使用laravl5在更新时忽略空表单值

问题描述 投票:0回答:2

无论如何要删除空表单值表单request-> all()方法?这是我在更新时尝试做的事情,换句话说,只是填写表格值。

 $data = request()->except(['_token','id']);

 DB::table($table)->where('id',$id)->update($data);

注意:我有动态生成的列,所以我想我不能在参数列表中使用这些列。

这会更新行的所有列,但我想只更新那些值已填充的列,并且其余的列/字段保持相同的旧值

laravel-5 laravel-eloquent laravel-query-builder
2个回答
1
投票

看看array_filter

// All posted data except token and id
$data = request()->except(['_token','id']);

// Remove empty array values from the data
$result = array_filter($data);

// update record
DB::table($table)->where('id', $arr)->update($result);

希望这可以帮助。


0
投票
// app/controllers/GiftsController.php

public function update($id)
{
    // Grab all the input passed in
    $data = Input::all();

    // Use Eloquent to grab the gift record that we want to update,
    // referenced by the ID passed to the REST endpoint
    $gift = Gift::find($id);

    // Call fill on the gift and pass in the data
    $gift->fill($data);

    $gift->save();
}

我在this tutorial找到了这段代码并且像魅力一样。我希望它有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.