Laravel表单模型绑定未提交

时间:2014-10-08 01:33:07

标签: php forms laravel model

我在使用L4的表单模型绑定时遇到了一些麻烦。我的表单正在填充,路由正确,但它没有正确提交。

控制器:

public function edit($id)
{
   $transaction = Transaction::where('id', '=', $id)->get();
    return View::make('transaction')->with('transactions', $transaction);

}

public function update($id)
{
    $transaction = Transaction::find($id);
    $input = Input::all();
    $transaction->status = $input['status'];
    $transaction->description = $input['description'];
    $transaction->save();
}

查看:

@foreach($transactions as $transaction)
{{ Form::model($transaction, array('route' => array('transactions.update', $transaction->id))); }}
{{ Form::text('description'); }}
{{ Form::select('status', array('R' => 'Recieved', 'S' => 'Shipped', 'P' => 'Pending'), 'R'); }}
{{ Form::submit('Submit'); }}
{{ Form::close(); }} 
@endforeach

1 个答案:

答案 0 :(得分:4)

我假设您的transactions.*路由是通过Route::resource()生成的。

Per the documentation,Laravel为资源生成以下路由:

Verb      Path                        Action  Route Name
GET       /resource                   index   resource.index
GET       /resource/create            create  resource.create
POST      /resource                   store   resource.store
GET       /resource/{resource}        show    resource.show
GET       /resource/{resource}/edit   edit    resource.edit
PUT/PATCH /resource/{resource}        update  resource.update
DELETE    /resource/{resource}        destroy resource.destroy

您会看到resource.update期待PUT/PATCH请求,但Laravel forms default to POST

要解决此问题,请将'method' => 'PUT'添加到表单选项数组中,如下所示:

{{ Form::model($transaction, array(
    'method' => 'PUT',
    'route'  => array('transactions.update', $transaction->id)
)); }}

这会在您的表单中添加一个隐藏的输入<input type="hidden" name="_method" value="PUT" />,告诉Laravel将请求伪装成PUT