10

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 Answers2

23

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.

amphetamachine
  • 27,620
  • 12
  • 60
  • 72
9

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?

Donkarnash
  • 12,433
  • 5
  • 26
  • 37