0

Here is a request from my Vue component:

 submit() {
      axios
        .put(`/api/posts/${this.slug}`, this.fields, {
          headers: { "content-type": "multipart/form-data" },
        })
        .then((res) => {
          //  some logic
        })
        .catch((error) => {
          // some logic
        });
    }

api.php

Route::group(['prefix' => 'posts', 'middleware' => 'auth:sanctum'], function () {
    Route::put('/{post:slug}', [PostController::class, 'update']);
});

put method doesn't work. I get the following error xhr.js:220 PUT http://127.0.0.1:8000/api/posts/test-title-updated-33 422 (Unprocessable Content) but when I replace put with post everything works as expected. I don't understand why put is not working.

Alphy Gacheru
  • 489
  • 1
  • 9
  • 28
  • 422 looks like you have validation in put route and did not pass them. Check your validation logic in put method and fields in axios request – Maksim Sep 27 '22 at 18:05
  • Yes, I do. I submit a form that is filled and it still fails the validations but when I switch to `post` the validations only fail when the form is not filled and pass when the form is filled. Strange to me. – Alphy Gacheru Sep 27 '22 at 18:10
  • Same validation rules, same input - and fail only on put, not post? Compare deeply, make sure inputs and rules are same – Maksim Sep 27 '22 at 19:06
  • 2
    @AlphyGacheru I think the answer is here https://stackoverflow.com/a/65009135/6106487 – Onur Uslu Sep 27 '22 at 19:12
  • @Maksim Yes, everything is the same. I'm only changing the methods but the recommended link by Onur clears the air on what is happening. – Alphy Gacheru Sep 27 '22 at 19:37
  • 1
    @OnurUslu Yes, that solves and my problem explains the reason for the result I'm getting as well. Thanks! – Alphy Gacheru Sep 27 '22 at 19:38

1 Answers1

0

Because HTTP PUT is not recognized by HTML standard.

You need to add POST type of method only but for update you can add a small flag with POST request for a PUT/PATCH type of operation.

axios.post(`/api/posts/${this.slug}`, { // <== use axios.post
     data: this.fields,
     _method: 'patch'                   // <== add this field
})
NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22
  • Thank you for the answer. It doesn't work but passing put/patch method in the formData object works. Answer was provided in the link attached above. – Alphy Gacheru Sep 28 '22 at 07:46