Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

petersowah's avatar

Multiple upload with Laravel

Hi..I would like to know if there's a way to have multiple uploads in laravel.Checked the doc but couldn't get any.Haven't found a suitable package yet. Thanks.

0 likes
14 replies
DCV's avatar

Multiple uploads is supported natively. Just need to do this in your form:

Form::file('myfile[]', ['multiple' => 'multiple']);

and when processing, you can reference them like:

foreach(Input::file("myfile") as $file) {
    //process each file
}
8 likes
atorscho's avatar

@DV, I am using Laravel 5.1 and trying to make it work, but cannot. Maybe in latest versions this feature has been removed?

Duffleman's avatar

@atorscho The Form facade is not included by default in Laravel installations, so if that is where it fails, then there is your problem, you should build the HTML form yourself, or use composer to require illuminate\html. After you include your ServiceProviders and Facades in config/app.php, you can use the Form facade to build the form.

If it is breaking during the foreach loop, then can you include some logs, or an error message?

atorscho's avatar

@Duffleman, everything's ok with that, I have already required this package in my composer file.

The problem is when I call $request->file('images') I get null. And my markup is exactly the same as above. Input name contains "[]" and "multiple" attribute too. It's only the problem with that null.

jekinney's avatar

Did you set encryption type on the form element to allow file uploads?

jekinney's avatar

Also the Dropbox js plugin might ease your issues too.

1 like
simondavies's avatar

i use http://www.dropzonejs.com/ quiet a bit as it gives feedback etc and works wonderful with the Laravel native File and Request items, and if i need to manipulate say images i also combine it with Intervention/Image package.

IanOlson's avatar

@simondavies Do you have an example of using Dropzone inside an existing form, so a form that has more than just Dropzone inside of it? I'm trying to get this working in 5.2.*, and not seeing files coming through to my Request object on the post method.

simondavies's avatar

@IanOlson So your trying to not only upload your normal dropzone details but also some other form input content?

I havent got anything to had at this precise time as away form those files. But to do this you need to do the following within your Dropzone instance.

You update the form data that is sent to grab your other form details and append it to the form data before sending, so something like:

  myDropzone.on("sending", function(file, xhr, formData) {
                // get the additonal form details.
                var formItemA = $('#formNameA').val(),
                    formItemB = $('#formNameA').val();
                //-- append to the form data on sending
                formData.append("itemA", formItemA);
                formData.append("itemB", formItemB);
          });   

Basically as Dropzone begins to send, we grab the other input files and append hem to the main request object.

I gather this is what your doing.

Then within Laravel i do something like.

if($request->hasFile('file')){
        //-- form details
        $details = $request->all();
        //-- file details
        $files = $request->file('file');
      .....

Hope this helps in a way..

simondavies's avatar

@IanOlson Actually here is a JS Class i did for a project a little while ago that I used, might help:

**SubmissionForm.js

"use strict";
/**
 * main site JS class
 */
(function(window){
    //-- private vars
    var form,
            formName,
            tokenHeader = $('meta[name="_token"]').attr('content'),
            submitBtn = $('#submitentry'),
            formValid = false,
            errors = {},
            errorWrapper = $('.form-errors-wrapper'),
            errorContainer = $('.form-errors-wrapper .errors');

    /**
     *  contructor
     */
    function SubmissionForm(){
         $.ajaxSetup({headers: { 'X-CSRF-Token': tokenHeader}});
         //** Dropzone settings **/
        Dropzone.autoDiscover = false;
    }   
    /**
     * submission form 
     */
    SubmissionForm.prototype.Init  = function(the_form,form_id, accepted_files){
            var uploadURL = $('#upload-dropzone').data('submit-url');
            form = $(the_form);
            formName = form;

            //-- upload documents
           var formDropdown = new Dropzone("#upload-dropzone",{
                headers: { 'X-CSRF-Token': tokenHeader},
                url : uploadURL,
                method : 'post',
                maxFilesize: 40, // MB
                uploadMultiple : true,
                acceptedFiles : accepted_files,
                dictDefaultMessage : 'Drag file(s) here to upload, or click to select one.<sup>✝</sup>',
                addRemoveLinks: true,
                autoProcessQueue: false,
                parallelUploads: 100,
                maxFiles: 40
           });
            /**
             * Success response of upload and form data
             */
            formDropdown.on("successmultiple", function(file, response, xhr) {
                formDropdown.removeAllFiles();
                errors = {};
                if(response.success === 'true' || response.success == true) {
                    //-- redirect to the thank you page
                    window.location.replace(response.redirect);
                } else {
                 errors['message'] = 'There was a problem with your entry.'
                _displayFormError(errors);
            }
            });
            
            /**
             * Error on form upload/submission
             */
            formDropdown.on("errormultiple", function(file, response, xhr) {
                formDropdown.removeAllFiles();
                errors = {};
                if(xhr && xhr.status === 422){
                    //-- loop through the error messages
                    if(response.success === false){
                            errors['message'] = response.message;
                        } else {
                            $.each(response, function(key, error){ errors[key] = error[0]; });
                     }
                } else {
                    errors['message'] = 'Sorry, There is the following error: ' + ((xhr && xhr.statusText) ? xhr.statusText : response);
                }

                $('.processing').removeClass('show');
                submitBtn.attr('disabled',false);
                _displayFormError(errors);
            });
            /**
             * prior to sending the uploads lets append to the fomr data the form values
             */
            formDropdown.on("sendingmultiple", function(file, xhr, formData) {
                //-- add the other form data to the sending process
                var formDetails = form.serializeArray();
                $.each(formDetails, function(i, field){
                    formData.append(field.name, field.value);
                });
            });

            /**
             * Submit form 
             */
             submitBtn.on('click',function(evt){
                evt.preventDefault();
                evt.stopPropagation();
                errorWrapper.removeClass('show');
                //-- init the upload
                var areThereFiles = formDropdown.getQueuedFiles();
                if(areThereFiles.length > 0 ){
                    $('.processing').addClass('show');
                    $(this).attr('disabled',true);
                    formDropdown.processQueue();
                } else {
                    _displayFormError({'files' : 'Please select a file to upload.'});
                }
            })
    }

    /**
     * display the form errors to the user
     */
    function _displayFormError(form_errors){
            errorContainer.html('');
            var displayErrors ='';
            $.each(form_errors, function(key, message){
                displayErrors += '<li>' + message + '</li>';
            });
            errorContainer.append(displayErrors);
            errorWrapper.addClass('show');
    }

    /**
     * set up any date pop ups on the form
     * @param input_id 
     */
    function _setUpDatepicker(input_id, options){
        $(input_id).datepicker(options);
     }

    //-- return the window object
    window.SubmissionForm = SubmissionForm;

})(window);

Called

varAcceptedFiles = 'image/*, .doc, .docx, .pdf, .mov, .mp4, .mpeg, .mpg, .avi, .pages'; 
    var submitForm = new SubmissionForm('#form','#formID', AcceptedFiles);

Form page:

  <div class="upload-wrapper dropzone" id="upload-dropzone"
                data-submit-url="{{route('page.upload')}}">
        </div>

The Laravel controller i have is:

    public function submitUpload(UploadFormRequest $request){
        return $this->myRepo->uploadEntry($request);
}

Then the repo is:

 public function uploadEntry($request){
       if($request->hasFile('file')){
      //-- form details
      $details = $request->all();
      //-- file details
      $files = $request->file('file');
          
          //-- DO STUF  HERE

     //-- add form detail to details table
    $submission = new Yserdetails();
            $entry = $submission->create($details);
    
    //-- loop through files and upload to users folder and save
            foreach ($files as $file) {
                $file_name = $file->getClientOriginalName();
                $file->move($destination_path, $file_name);
                $charlies_files = new UsersFiles();
                $charlies_files->users_id = $entry->id;
                $charlies_files->file_name = $file_name;
                $charlies_files->location = $destination_path;
                $charlies_files->save();
            }
        
    }
  }

Hopefully this will be more useful......

1 like

Please or to participate in this conversation.