Recently I have started a Laravel 5.4 project and I found something I don't quite understand and I'm posting this question hoping to solve this issue and find out if it's expected behaviour or a bug.
The thing is, I'm submitting an update form which looks like so:
<form id="post-form" action="{{url('admin/posts/'.$post->id)}}" method="POST">
{{ csrf_field() }}
{{ method_field('PUT') }}
<!-- Some fields -->
</form>
And I try to validate that request on the controller method:
$validator = Validator::make($request->all(), [
// Fields to validate
]);
if ($validator->fails()) {
return back()
->withErrors($validator)
->withInput();
}
My problem comes when the validation fails and the redirect is performed, because I get a code 405 error MethodNotAllowedHttpException
.
Indeed, the url is correct but the method is wrong, as shown in the HTTP headers:
Request URL:https://myproject.dev/admin/posts/1/edit
Request Method:PUT
Status Code:405
Remote Address:127.0.0.1:443
Referrer Policy:no-referrer-when-downgrade
It should be a GET instead of a PUT. My best guess is that is using the _method property of the $request
object to redirect, instead of using the GET method.
A dump($request->all())
right before the redirect call:
array:19 [
"_token" => "XOtwEeXwgnuc8fNqCwxkdO992bU6FObDwTuCg1cJ"
"_method" => "PUT"
//fields
]
Some things I have already tried with no luck:
- Unsetting the _method from the request:
unset($request['_method'])
Name the route and redirect based in that name:
// The routes file (routes/web.php) Route::get('posts/{id}/edit', 'PostsController@edit')->name('edit-post'); // The redirect (controller) return redirect()->route('edit-post', ['id' => 1]) ->withErrors($validator) ->withInput();
Specify the url in the redirect
// The redirect (controller) return redirect('admin/posts/'.$post->id.'/edit') ->withErrors($validator) ->withInput();
So how could I perform that redirect with a normal GET method? Is this an expected behaviour? Thank you in advance, any advice or hint is much appreciated.