Reputation: 227
I am using Laravel 5.6 and MySQL. I am going to update the student table using the following controller function:
public function update(Request $request, $id)
{
$students = Student::find($id);
$students->name = $request->input('name');
$students->town = $request->input('town');
$students->save();
}
and the update form action looks like this:
<form action="{{route('student.update',$students->id)}}" method="POST">
{{csrf_field()}}
and my route is define like this:
Route::resource('student','StudentController');
My problem is, when I click the update button in the form it generates the following error message
1/1) MethodNotAllowedHttpException
What's wrong?
Upvotes: 3
Views: 7918
Reputation: 31
<form action="/admin/manage-banners/{{$id}}" method="POST" enctype='multipart/form-data'>
@csrf
@method('PUT')
//rest of your code
...
</form>
The above code works for me in laravel 9.
{!! method_field('PUT') !!}
gave me error.
Upvotes: 1
Reputation: 534
You are using wrong HTTP method, update
method on Route::resource
route requires that request is sent with PUT/PATCH HTTP method.
Since HTTP forms doesn't support PUT/PATCH as method you should spoof HTTP method by using Blade directive @method('PUT')
inside form.
<form action="{{route('student.update',$students->id)}}" method="POST">
{{csrf_field()}}
{!! @method('PUT') !!}
</form>
Upvotes: 5
Reputation: 879
Verify your route by executing the command :
php artisan route:list
and do check if your request is either sent with 'PUT or PATCH'
I see you are trying to update $student. So instead $student->save()
You may do it like this :
public function update(Request $request, $id)
{
try
{
$input = $request->all();
$student = Student::where('id',$id)->update($input);
return $student;
}catch(QueryException $ex) {
return ['success'=>false, 'error'=>$ex->getMessage()];
}
}
Upvotes: 0