PATCH and PUT Request Does not Working with form-data - php

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.

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>

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

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

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).
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]).
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!

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

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';
}

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.

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.

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?

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.

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");
});
},

I know this article is old.
But unfortunately, PHP still does not pay attention to form-data other than the Post method.
But you can use the library I wrote for this purpose:
composer require alireaza/php-form-data
You can also use composer require alireaza/laravel-form-data in Laravel.

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

Related

Phalcon 5 - Sending post request to controller results in empty post data

I'm using a docker setup with php 8.0.15 + phalcon 5.0.0beta2 and i'm trying to do a simple post request using the fetch api to a route.
/* inside router.php */
$apiGroup = new Router\Group();
$apiGroup->setPrefix('/api');
$apiGroup->addPost('/user', 'UserApi::post');
/* somewhere in my controller action */
$data = [
'email' => $this->request->getPost('email', [ Filter::FILTER_EMAIL ]),
'password' => $this->request->getPost('password', [ Filter::FILTER_STRING ]),
];
/* in my js */
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(someData)
}).then(dostuff);
My problem is that $this->request->getPost('email') returns null and when debugging I saw that $_POST is also empty. Using $this->request->getRawBody() and $this->request->getJsonRawBody() do yield results since my data is actually there. I could very well just use getJsonRawBody(), but i'm wondering why the behaviour? (I used phalcon 3.* for another project and it worked just fine)
Thanks.
The documentation for Phalcon's Request object explains that it is primarily a wrapper around PHP's native "superglobals", such as $_POST. In particular:
The $_POST superglobal contains an associative array that contains the variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. You can retrieve the data stored in the array by calling the getPost() method
Note that important caveat that this array is only populated when using two specific content types - specifically, the two content types that browsers use when submitting HTML forms. Form processing is the original task PHP was built for, and it can handle things like file uploads; but it doesn't natively do anything with JSON, XML, or other input types.
(As an aside, that documentation is subtly wrong: despite its name, $_POST will be populated for any HTTP method with an appropriate request body, e.g. PUT, just as $_GET is populated even when the method is POST.)
In your request, you're not using those content types, because you're posting a JSON string, so PHP doesn't populate $_POST, and Phalcon doesn't have anything to read with getPost().
As you've discovered, there's a separate method which allows you to decode the JSON body to a PHP array:
getJsonRawBody(): Gets decoded JSON HTTP raw request body
There's no mention of JSON at all in the Phalcon 3.4 Request documentation so I'm not sure whether that functionality has changed, you've misremembered, or you were using some additional plugin or configuration.
The REST tutorial shows usage of getJsonRawBody() in both the 5.0 version and the 3.4 version.

How to accept the PUT request data in laravel? [duplicate]

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.
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>
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
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
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).
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]).
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!
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
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';
}
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.
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.
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?
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.
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");
});
},
I know this article is old.
But unfortunately, PHP still does not pay attention to form-data other than the Post method.
But you can use the library I wrote for this purpose:
composer require alireaza/php-form-data
You can also use composer require alireaza/laravel-form-data in Laravel.
You can use post method.
const form = new
just append form.append('_method', 'PATCH');

$_REQUEST php equivalent in node js

Actually I am using a third party api url of Plivo.
There I need to supply a URL with POST method on which they are gonna post call data .
I have provided url in lumen and able to get the data posted by third party url using $_REQUEST successfully.
Now I am trying implement the same in node js express like:
exports.plivoIvrCallback = function (req, res) {
console.log(req);
}
but I am not getting anything in req or req.body !
So what might be node js equivalent to $_REQUEST in php.??
Please install body-parser package and then try.
you can install body-parser (as suggested by # Mr.Gandhi) or any other requests parsers you want, than add the following line at the start of your handler:
let request = Object.assign(req.query, req.body); // you can also add here req.params etc...
and use request from now on.

How does this HTTP request work?

To begin, this question deals primarily with HTTP requests, BackboneJS, some sort of RESTful API (such as Slim API), and how these things work with each other. Additionally, this question is coming from someone who doesn't have much experience on the server-side, other than just handling basic PHP/MySQL stuff.
I've been looking at Backbone, and I've seen some tutorials regarding the use of RESTful APIs on the back-end (including this one from 9bit).
I also read this answer to a StackOverflow question (Understand BackboneJS REST Calls).
If I open up a JS file, and type type in some code to send a POST request such as this:
(function() {
var http = new XMLHttpRequest();
var value = '{ "prop1": "value 1", "prop2": "value 2" }';
http.open('POST', 'dir', true);
http.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
http.setRequestHeader('Content-Length', value.length);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(value);
})();
I see in the console that it sent a POST request looking something like this:
Method: POST
Body: { "prop1": "value 1", "prop2": "value 2" }
Location: http://localhost/~myusername/Todo/dir/
And then, since it's just my local server, the server sends back a response with the basic HTML page that shows the files in that directory, etc.
I tried using a GET request to retrieve a similar JSON object as well, but obviously I couldn't get anything from that location, presumably because the object I was trying to request from some empty folder doesn't even exist anywhere.
My question is, when you use a BackboneJS method such as .save(), from what I understand, it might use, in that instance, a PUT method to send a request with a body of an object, perhaps parsed as a string, to a directory, such as 'article/id', with 'id' possibly being something like '43' (potentially the corresponding id of whatever model's properties you sent). So...
1) What does an API, such as Slim do with that request?
2) Where is it saving those object properties to (a MySQL database)?
3) Is there a file, such as 'index.php', sitting in the directory 'article', in which a script grabs the parameters in the body of the POST requests and uses though to communicate with the MySQL database? (I'm wondering why the location is simply a 'folder', such as '/article'. To put it in another context, whenever you type in a website like 'http://www.mywebsite.com', the server will automatically look for an 'index' page in that directory, such as 'index.html', and automatically open that file as the default file of that directory. Is that same type of thing happening in the context of using a location '/somefoldername' as the location of the HTTP request)?
Basically, it just looks strange to me that you would send an HTTP request to just some folder, and not a specific PHP file (for example) that would handle the request and communicate with a database. Using BackboneJS with a RESTful API, would our theoretical folder '/article' even exist, or is that just appended to the URL for some reason?
Thank you very much.
Since you asked your questions in the context of Slim, I'm going to answer them that way, although much of the information will generally apply to other web applications/frameworks.
What does an API, such as Slim do with that request?
Not to be to cheeky, but it does whatever you (or the API developer) wants it to do (more on that shortly).
Where is it saving those object properties to (a MySQL database)?
In general, those object properties are being used to create a resource (POST) or to updated a resource (PUT), and most likely the resource is being persisted in some sort of storage, be it an RDMS or a NoSQL solution.
Is there a file, such as 'index.php', sitting in the directory 'article', in which a script grabs the parameters in the body of the POST requests and uses though to communicate with the MySQL database?
Here's where things get interesting, IMHO. Considering the route article/id, here's what happens in a Slim application:
A request is received at example.com/article/22
The request is routed to a front controller script which, based on the request URI and HTTP method, makes a decision about what to do with the request.
If a PUT route for article exists, then the application code perhaps would take the request body and update the resource identified by the provided id.
With that in mind, in a Slim application, likely the only web accessible file is index.php. What appear to be directories are merely routes defined in the application's index.php that Slim used to make decisions about how to handle requests. With that in mind . . .
Using BackboneJS with a RESTful API, would our theoretical folder '/article' even exist, or is that just appended to the URL for some reason?
In the context of a Slim application, no, /article wouldn't exist as a directory, but rather a route.
Perhaps this won't help much, but this is what a portion of that index.php routing file might look like on the Slim side:
$app->post('/article', function () {
// Get data from post
// Create resource
});
$app->get('/article/:id', function ($id) {
// Return an article resource identified by $id
});
$app->put('/article/:id', function ($id) {
// Use $id to retrieve resource from storage
// Update resource with request data
});

laravel 4: why is Request::header() not getting the specified header?

I'm trying to get a header value with:
Request::header('csrf_token')
though, my firebug says in the headers that I have the csrf_token set to baMDpF0yrfRerkdihFack1Sa9cchUk8qBzm0hK0C. In fact, I can get that csrf_token instead with a native php code:
getallheaders()['csrf_token']
Now the question is am I doing my XSRF-protection right? or maybe there is a flaw in that php code I did, that I really have to use buggy laravel 4 function
Request::header('csrf_token')
which returns nothing but blank. And I just missed something. maybe in my Laravel 4 configurations, etc?
P.S: I am using AngularJS, but maybe it does not matter what clientside I use. I have this link as my guide: How to send csrf_token() inside AngularJS form using Laravel API?
I solved the problem by removing the underscore '_' in csrf_token so it would be crsftoken instead.
Request::header('csrf_token'); // Not working
Request::header('csrftoken'); // Working!
I think the problem there is that in the following answer at How to send csrf_token() inside AngularJS form using Laravel that you used, the csrf_token is not sent in the header of your XMLHttpRequest but in the form it self.
You need then to filter it in your laravel backend as a regular Input field. See below for a working example :
Route::filter('csrf_json', function()
{
if (Session::token() != Input::get('csrf_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
UPDATE
If you want to use headers in Angular, you would rather write something like :
$httpProvider.defaults.headers.common['Authorization'] = TOKEN;
In order to aplly a new header to your XMLHttpRequests. Then it is easily catchable even with raw php such as :
$aHeaders = getallheaders();
if (Session::token() != $aHeaders['authorization']) etc.
Problem
Laravel is removing headers with an underscore in the name when retrieving them with the Request::header() method. Additionally, all header names are converted to lower case in the Request::header() method.
Short Solution
On the frontend, replace all underscores in header names with dashes. csrf_token becomes csrf-token
Long Solution
Add the Laravel CSRF token as an Angular constant on your main page / layout.
<script>
angular.module("myApp").constant("CSRF_TOKEN", "<?php echo csrf_token(); ?>");
</script>
Add the token as a default header for all your requests in Angular.
angular.module("myApp").run(function($http, CSRF_TOKEN){
$http.defaults.headers.common["csrf-token"] = CSRF_TOKEN;
})
Have your csrf filter in Laravel check for a match in the headers rather than an input.
/**
* Check that our session token matches the CSRF request header token.
*
* #return json
*/
Route::filter("csrf", function() {
if (Session::token() !== Request::header("csrf-token")) {
return Response::json(array(
"error" => array(
"code" => "403",
"message" => "Ah ah ah, you didn't say the magic word.",
),
));
}
}
Request::header() is indeed used for the retrieval of headers, but check where the token is being set.. the CSRF token should be placed into the session by Laravel, and then it can be accessed through the Session::token() method.
If you look at the HTML generated through calls to the Form:: class, you'll see a hidden element called _token, which should then be compared to the token in the session. You can access that using Input::get('_token'), as with any other incoming GET or POST variable.
...However, all this shouldn't really be necessary, as it can be managed easily through the pre-defined CSRF filter in filters.php, just add that filter to the desired route or route group and you'll be protected, without having to get into the details of it.
the problem is with the Symfony Request object, which is extended in the Laravel framework. See this github thread
https://github.com/laravel/framework/issues/1655#issuecomment-20595277
The solution in your case would be to set the header name to HTTP_CSRF_TOKEN or HTTP_X_CSRF_TOKEN if you like prefixing X to your custom http headers.

Categories