Asur
Asur

Reputation: 4017

Laravel 5.4 redirect taking method from request object

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:

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.

Upvotes: 2

Views: 2078

Answers (1)

Jerodev
Jerodev

Reputation: 33186

You need a separate put route in your routes.php file.

Route::get('posts/{id}/edit', 'PostsController@edit')->name('edit-post');
Route::put('posts/{id}/edit', 'PostsController@edit')->name('edit-post');

The get function means this route will handle routes using the GET method. You need to add a put to handle requests using the PUT method. All available route methods are available in the documentation.


You can also use the match function to match multiple methods in one line. Like so:

Route::match(['get', 'put'], 'posts/{id}/edit', 'PostsController@edit');

Upvotes: 1

Related Questions