Home > database >  Sending multipart/form-data with PUT request doesn't work in Laravel
Sending multipart/form-data with PUT request doesn't work in Laravel

Time:12-08

I am trying to send an HTTP PUT request with "Content-Type": "multipart/form-data" to a Laravel application. When I change the method to POST it works.

$a = $request->all(); // With PUT this is empty but with POST it works fine. 

The client-side executes the following code:

axios({
    method: "post", // when I try method:"PUT" and change the content type 
    url: "/api/offer",
    data: fd,
    headers: {"Content-Type": "multipart/form-data"} // here change to "x-www-form-urlencoded" it the $a array on backend is empty! 
}).then(response => {
    console.log("/offer/"   response.data)
    if (response.data)
        window.location.replace("/offer/"   this.offer.id);
    else {
        console.log("show a message that something went wrong! ")
    }
}).catch(function (error) {
})

I could not find anywhere in the docs that PUT can't send "multipart/form-data"

So, can PUT send "multipart/form-data" or only POST can do that in general or it is only a PHP / Laravel Issue?

Edit: Also, what difference does it make to use PUT instead of POST other than to comply with HTTP protocol and CRUD operation properly?

CodePudding user response:

Laravel (HTML Forms) do not work great with Put requests so you'll need to spoof a POST request as if it was a PUT or PATCH request. On Axios you use the .post verb but within your form data you append

_method: "put"

Information from the official documentation: https://laravel.com/docs/8.x/routing#form-method-spoofing


Excerpt from the documentation:

HTML forms do not support PUT, PATCH, or DELETE actions. So, when defining PUT, PATCH, or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method

CodePudding user response:

I ran into this issue a few weeks ago myself with a Symfony 5.3 project. It only worked with POST Requests, not with PUT. Here's an issue from the Symfony GitHub that explains it in more detail.

To my understanding the issues lies within the PHP implementation of those requests. The HTTP standard "PUT" supports it, but PHP does not. Here's also a link to the bug from the PHP bugtracker.

  • Related