PATCH and PUT Request Does not Working with form-data

PhpLaravelHttpPostman

Php Problem Overview


I am using Laravel to create a RESTFUL application and I test the application with Postman. Currently, there is an issue for PATCH or PUT if the data sent from Postman with form-data.

// Parameter `{testimonial}` will be sent to backend.
Route::post  ('testimonials/{testimonial}', 'TestimonialController@update');

// Parameter `{testimonial}` will not be sent to backend (`$request->all()` will be empty) if sent from Postman with form-data.
Route::patch ('testimonials/{testimonial}', 'TestimonialController@update');
Route::put   ('testimonials/{testimonial}', 'TestimonialController@update');
  • Using form-data, $request->all() will be okay for POST.
  • Using x-www-form-urlencoded, $request->all() will be okay for PATCH, PUT, and POST.
  • However, if I am sending PUT and PATCH with form-data from Postman, the $request->all() will be empty (the parameters will not be sent to backend).

Right now the solution is to use POST for updating a model. I want to know why PATCH and PUT is not working when sent with form-data from Postman.

Php Solutions


Solution 1 - Php

This is a known issue and the workaround suggestion as per the following Github comment is that when sending a PATCH / PUT requests you should do the following:

>You should send POST and set _method to PUT (same as sending forms) to make your files visible

So essentially you send a POST request with a parameter which sets the actual method and Laravel seems to understand that.

As per the documentation:

>Since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs. The @method Blade directive can create this field for you:

<form action="/foo/bar" method="POST">
    @method('PUT')

    ...
</form> 

Alternatively, you can use the method_field helper function to do the above:

>The method_field function generates an HTML hidden input field containing the spoofed value of the form's HTTP verb. For example, using Blade syntax:

<form method="POST">
    {{ method_field('PUT') }}
</form>

Solution 2 - Php

I learnt how to solve it here on this post and I'd like to share what did I do.

The following image is how I setup the Postman to send a HTTP POST request and go into PUT Request and make it receive my files.

I'm not sure whether it is the right way to do a RESTFul API. But it works fine

An example on Postman how to setup your HTTP Request

Solution 3 - Php

so as everyone mentioned above and explained everything, but still i dont see the answer for cases when using a REST API so i fallowed @Caique Andrade answer and send a POST request and formed my URL link like this:

url = 'https://yourwebsite.com/api/v1/users/$id?_method=PUT';

$id is the variable id for the user.

?_method=PUT is added to the url POST request to spoof the request and it works

in my case i used Dart in flutter and sent a post request using Http package Laravel catches that POST request as a PUT request

Solution 4 - Php

Laravel PATCH and PUT method does not work with form-data, it's known issue of Symfony and even PHP (Google for that - Laravel use many Symfony foundation packages, include Request).

  1. If you do not need to pass file(s) via request, change form-data to raw with json content-type. E.g: {"name":"changed"}. It will be read as php://input and your code should work well ($request->all() is now ["name" => "changed]).

  2. If you need to pass file(s), in my opinion, DO NOT pass it within the REST API methods. You can write another method to do whatever you need with your file(s) (E.g: POST form-data -> upload file -> update db -> return a file path/url/even its base64 content), then you can use its output/result to continue with your patch/put method (raw with json content-type). I always do that when I work with files in API.

Hope this help!

Solution 5 - Php

As mentioned, this isn't a symfony (or laravel, or any other framework) issue, it's a limitation of PHP.

After trawling through a good few RFCs for php core, the core development team seem somewhat resistant to implementing anything to do with modernising the handling of HTTP requests. The issue was first reported in 2011, it doesn't look any closer to having a native solution.

That said, I managed to find this PECL extension. I'm not really very familiar with pecl, and couldn't seem to get it working using pear. but I'm using CentOS and Remi PHP which has a yum package.

I ran yum install php-pecl-apfd and it literally fixed the issue straight away (well I had to restart my docker containers but that was a given).

That is, request->all() and files->get() started working again with PATCH and PUT requests using multipart/form-data.

I believe there are other packages in various flavours of linux and I'm sure anybody with more knowledge of pear/pecl/general php extensions could get it running on windows or mac with no issue.

Solution 6 - Php

As @DazBaldwin says, this is a php limitation and can be solve installing apfd extension. On windows just download the dll file here according to your system settings and put php_apfd.dll on path-to-php/ext directory finally put extension=apfd in php.ini file.

it worked for me on windows.

Solution 7 - Php

InertiaJS Solution

I had the same problem. When no file was send, everything works perfectly, but when i send a file, none of the fields make it to the backend.

It seems that it's a PHP limitation, receiving no file via put, as said here before.

So, for those using InertiaJS, you need to make a post - instead of a put - call and add _method: "put" to your inertia form, like this:

updateForm: this.$inertia.form({
			_method: "put",
			"other fields"
		}),

Your controller will understand it like a PUT call, but with the file accessible to the backend.

Source: https://inertiajs.com/manual-visits#method

Solution 8 - Php

I hope it is not too late, or if someone is seeking help with the FormData interface of JavaScript. Here is the solution, In Laravel, you can use @script47 answers above, for normal Ajax request you can append the data like this, (PS: I'm using same form for Add and Update so here is my code)

let _url = '';
let _type = 'POST';
let _formData = new FormData(this);
if(user_id == '' || user_id == null){
    _url = "{{ route('users.store') }}";
}else{
    _url = "{{ route('users.update', ':id') }}";
    _url = _url.replace(':id', user_id);
    _formData.append('_method', 'PUT');
    // _type = 'PUT';
}

Solution 9 - Php

The form media types do not have any semantics defined for PATCH, so it's really a bad idea to use them (see https://www.rfc-editor.org/errata/eid3169).

For PUT, the expected behaviour would be to store just the form-encoded payload (in that format). Is this really what you want here?

Solution 10 - Php

If You Route Method Is Patch And Use Postman For Api Request

If you want to send a file, for the controller, when using postman, you must set the sending mode to the post method and in the form-data section key = _Method Value = PATCH You do not have to set the file so that you do not encounter any errors when sending the request.

Solution 11 - Php

You can also create a custom function in your controller to update the product then create an api route.

  public function updateTestimonial($id, Request $request) {
    $testimonial = Testimonial::where('id', '=', $id)->first();
    //update logic
}

Api route

Route::post('updatetestimonial/{id}', 'Testimonial@updateTestimonial');

Use a post request and pass testimonial id.

submitForm() {
        let data = new FormData();
        data.append('id', this.testtimonial.id);
        data.append('description', this.testtimonial.description);
        axios.post("/api/updatetestimonial/" + this.testimonial.id , data, {
            headers: {
                'accept': 'application/json',
                'Accept-Language': 'en-US,en;q=0.8',
                'Content-Type': 'multipart/form-data',
            }
        }).then(({ data }) => {
             console.log("success");
        });
    },

Solution 12 - Php

You can use post method. const form = new just append form.append('_method', 'PATCH');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnotalentgeekView Question on Stackoverflow
Solution 1 - PhpScript47View Answer on Stackoverflow
Solution 2 - PhpCaique AndradeView Answer on Stackoverflow
Solution 3 - PhpRidha RezzagView Answer on Stackoverflow
Solution 4 - PhpvietanhytView Answer on Stackoverflow
Solution 5 - PhpDazBaldwinView Answer on Stackoverflow
Solution 6 - PhpDiego RodriguesView Answer on Stackoverflow
Solution 7 - PhpCarlos SallesView Answer on Stackoverflow
Solution 8 - PhpTayyab HayatView Answer on Stackoverflow
Solution 9 - PhpJulian ReschkeView Answer on Stackoverflow
Solution 10 - PhpafshindadashnezhadView Answer on Stackoverflow
Solution 11 - PhpJohn WanjemaView Answer on Stackoverflow
Solution 12 - PhpNasimView Answer on Stackoverflow