14

Having read this SO link,

PUT is most-often utilized for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.

From this answer,

... we need to send all the parameters of the data again.

In my controller, I have:

$student = Student::find($student_id);
$student->username = $request->username;
$student->email = $request->email;
$student->password = $request->password;
$path = $request->file('passport')->store('upload');
$student->passport = $path;

I have once used this same code for POST method and it worked, but while using it for APIs, I used POSTMAN form-data and got $request->all() to be null. Some said I should use x-www-form-urlencoded but this does not allow files upload.

2 Answers 2

36

This is actually an incapability of PHP itself. A PUT/PATCH request with multipart/form-data just will not populate $_FILES, so Laravel has nothing to work with.

Every once in a while, people report bugs like this when they find $request->all() returns null, thinking it's Laravel's fault, but Laravel can't help it.

Files are best sent as multipart/form-data and that sort of request will only populate $_FILES if it's a POST. No $_FILES, no $request->file().

In lieu of having this work as-expected in PHP, if it works using a POST, just use a POST.

Sign up to request clarification or add additional context in comments.

2 Comments

Wish I had known this before. Wracked my brain on this for more than a day.
The problem with this answer is that you now cannot use a resource controller with multipart/form-data because POST will route to the store function.
10

When the form contains uploaded file it works only with POST method - probably an issue with PHP/Laravel

If someone wants to use a PUT or PATCH request for form containing file uploads

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

    ...
</form>

via any javascript framework like vue

let data = new FormData;
data.append("_method", "PUT")

axios.post("some/url", data)

Using _method and setting it to 'PUT' or 'PATCH' will allow to declare route as a PUT route and still use POST request to submit form data

I have answered a similar question How to update image with PUT method in Laravel REST API?

1 Comment

Thats usefull :) tx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.