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?
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!