Laravel 5.1:如何为更新记录设置路由 [英] Laravel 5.1: How to set Route for update record
问题描述
我正在使用laravel 5.1
I am working with laravel 5.1
我正在使用拉拉韦尔(laravel)的路线.
I am using the routes of laravel.
我使用表单/HTML 进行插入/更新,但是卡在更新记录的路由中.
I used Form/Html for insert/update, but stuck in routing of update record.
这是用于重定向到route.php中的编辑页面的路径
Here is route for redirect to edit page in routes.php
Route::get('/company/edit/{id}','CompanyMasterController@edit');
在我的CompanyMasterController.php中
In my CompanyMasterController.php
public function edit($id)
{
$company = CompanyMasters::find($id);
return view('companymaster.edit', compact('company'));
}
我在edit.blade.php中的动作
My action in edit.blade.php
{!! Form::model($company,['method' => 'PATCH','action'=>['CompanyMasterController@update','id'=>$company->id]]) !!}
并在routes.php中执行此操作的路线
and route for this action in routes.php
Route::put('/company/update/{id}','CompanyMasterController@update');
我要更新的控制器动作.
My controller action for update.
public function update($id)
{
$bookUpdate=Request::all();
$book= CompanyMasters::find($id);
$book->update($bookUpdate);
return redirect('/company/index');
}
现在,当我单击提交"按钮时,它会给我:
Now when I click on submit button it gives me:
RouteCollection.php中的MethodNotAllowedHttpException
MethodNotAllowedHttpException in RouteCollection.php
我在做什么错了?
推荐答案
出现此错误的主要原因是因为您将表单设置为使用PATCH
方法提交,并且已设置了查找路径PUT
方法.
The main reason you're getting this error is because you set your form to submit with a PATCH
method and you've set your route to look for a PUT
method.
您拥有的两个初始选项要么在您的路线文件中使用与表单相同的方法,要么还可以将您的路线设置为:
The two initial options you have are either have the same method in your route file as your form or you could also set your route to:
Route::match(['put', 'patch'], '/company/update/{id}','CompanyMasterController@update');
以上内容将允许这两种方法都用于该路线.
The above will allow both methods to be used for that route.
或者,您可以使用route:resource()
https://laravel.com/docs/5.2/controllers#restful-resource-controllers .
这将处理所有基本的Restful路线.
This will take care of all the basic Restful routes.
然后进一步,您可以将以下内容添加到路由文件中:
Then to take it one step further you can add the following to your routes file:
Route::model('company', 'App\CompanyMasters'); //make sure the namespace is correct if you're not using the standard `App\ModelName`
然后您的资源路线将类似于:
Then your resource route would look something like:
Route::resource('company', 'CompanyMasterController');
然后在CompanyMasterController
中可以提示您的方法,例如
And then in CompanyMasterController
your methods can be type hinted e.g.
public function edit($id) {...}
将成为:
public function edit(CompanyMaster $company)
{
return view('companymaster.edit', compact('company'));
}
很显然,即使您不想这样做,也不必采用这种方法.
Obviously, you don't have to go with this approach though if you don't want to.
希望这会有所帮助!
这篇关于Laravel 5.1:如何为更新记录设置路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!