Search code examples
phplaravelfile-upload

Laravel $request->file() returns null


having trouble trying to upload files using Laravel on the back-end.

Issue

Laravel $request->file() method returns null.

Setup

I build up an AJAX request using superagent, debugged the request and everything seems fine. The Content-Length changes depending on the image I add, indicating an image has been added to the request. The Content-Type is also set to multipart/form-data.

// request headers
Content-Length:978599
Content-Type:multipart/form-data; 

// request payload
Content-Disposition: form-data; name="files"; filename="item-keymoment.png"
Content-Type: image/png

But I'm unable to get the file in Laravel. Using $request->file('files') returns NULL, but if I debug the $_FILES array, I noticed that a my file has been uploaded.

dd($request->file('files'))
// NULL

dd($_FILES);
// array:1 [
//   "files" => array:5 [
//     "name" => "item-keymoment.png"
//     "type" => "image/png"
//     "tmp_name" => "/tmp/phpipbeeM"
//     "error" => 0
//     "size" => 978274
//   ]
// ]

dd($request->files->all())
// []

What might be causing Laravel to ignore the file?
Content-Type of the input file not being application/octet-stream?

Below have answered the question.


Solution

  • You should add to the form tag enctype="multipart/form-data"

    For example:

    <form method="POST" action="{{route('back.post.new')}}" enctype="multipart/form-data">
    .............
    </form>
    

    Adding it you can use your custom Request.

    I hope this can you help!