【问题标题】:Laravel update controller with many inputs具有许多输入的 Laravel 更新控制器
【发布时间】:2014-04-23 19:27:25
【问题描述】:

我有一个资源,我正在尝试设置更新控制器。在我的情况下,我的编辑表单有很多输入,我需要用它们更新数据库,但是数据库中可能有一些列没有被编辑表单更改。所以我有这样的控制器:

public function update($id)
{

    $hostess = Hostess::find($id);

    $inputs=Input::all();

    foreach ($inputs as $key => $value) {
        $hostess->$key= $value;
    }

    if ($hostess->save())
    {
        return Redirect::route('hostesses.show', $hostess->id);
    }

    return Redirect::back()->withInput()->withErrors($hostess->getErrors());
}

这给了我一个错误,因为我在我的视图中使用 PUT 并且我得到了

 Column not found: 1054 Unknown column '_method' in 'field list'

因为我的 Input::all() 正在获取 PUT 方法的隐藏输入。我可以为此使用 Input::except() ,但这是用 laravel 更新的正确方法吗?

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    你实际上可以这样做:

    $hostess   = Hostess::find($id)
    
    $post_data = Input::all();
    // or
    $post_data = Input::except('_method');
    
    // warning untested if block below
    if ($hostess->update($post_data))
    {
        return Redirect::route('hostesses.show', $hostess->id);
    }
    
    return Redirect::back()->withInput()->withErrors($hostess->getErrors());
    

    只要这样就可以更新所有可用的键值对。

    请注意,您必须将columns 添加到模型中的$fillable 属性以避免质量分配警告。

    【讨论】:

    • 你的答案是要走的路,但为了让它更好地添加作为替代 fill(Input::all()) 或 new Hostess(Input::all()) 更简单,但是当模型上设置了 $fillable 时。
    • 谢谢,这看起来是正确的方法。
    【解决方案2】:

    你可以这样做:

    $inputs = Input::all();
    $inputs = array_except($input, '_method');
    

    【讨论】:

      猜你喜欢
      • 2012-03-23
      • 2020-10-18
      • 2018-04-15
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 2017-04-16
      相关资源
      最近更新 更多