Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PUT method in Laravel API with File Upload

Tags:

put

laravel

api

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.

like image 364
Owonubi Job Sunday Avatar asked Dec 11 '22 00:12

Owonubi Job Sunday


1 Answers

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.

like image 148
amphetamachine Avatar answered Dec 24 '22 21:12

amphetamachine