【问题标题】:Ignore empty form values on update using laravl5使用 laravl5 在更新时忽略空表单值
【发布时间】:2018-04-01 16:48:40
【问题描述】:

是否有删除空表单值表单 request->all() 方法? 这就是我在更新时尝试做的事情,换句话说,只发布填写的表单值。

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

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

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

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

【问题讨论】:

    标签: laravel-5 laravel-eloquent laravel-query-builder


    【解决方案1】:
    // 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 中找到了这段代码,它的作用就像魅力一样。希望对你有帮助。

    【讨论】:

      【解决方案2】:

      看看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);
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2014-06-10
        • 1970-01-01
        • 1970-01-01
        • 2021-04-19
        • 1970-01-01
        • 2016-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多