Laravel 5.1: How to set Route for update record

╄→гoц情女王★ 提交于 2019-12-13 16:26:17

问题


I am working with laravel 5.1

I am using the routes of laravel.

I used Form/Html for insert/update, but stuck in routing of update record.

Here is route for redirect to edit page in routes.php

Route::get('/company/edit/{id}','CompanyMasterController@edit');

In my CompanyMasterController.php

public function edit($id)
   {
      $company = CompanyMasters::find($id);

      return view('companymaster.edit',  compact('company'));
   }

My action in edit.blade.php

{!! Form::model($company,['method' => 'PATCH','action'=>['CompanyMasterController@update','id'=>$company->id]]) !!}

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:

MethodNotAllowedHttpException in RouteCollection.php

What am I doing wrong?


回答1:


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.


Alternatively, you can use route:resource() https://laravel.com/docs/5.2/controllers#restful-resource-controllers.

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

And then in CompanyMasterController your methods can be type hinted e.g.

public function edit($id) {...}

Would become:

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.

Hope this helps!



来源:https://stackoverflow.com/questions/35036192/laravel-5-1-how-to-set-route-for-update-record

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!