1

Environment:

  • Laravel Version: 5.7
  • PHP Version $ php --version: PHP PHP 7.1.3 (cli)
  • Database Driver & Version $ mysql --version: mysql Ver 8.0.23-0ubuntu0.20.04.1

Problem Statement:

Unable to dd code to iterate multiples file upload inside Controller. And dd($files) is returning last uploaded file instead file array or object

$files = $request->file('file');
        
foreach ($files as $file){
    dd($file);
}

Files & Configuration:

upload.blade.php

<form>
    <input name="file[]" class="form-control" type="file" id="file" multiple required>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

<script>
    $("form").submit(function(evt){  
        evt.preventDefault();
        var formData = new FormData($(this)[0]);
    
        $.ajax({
            url: '{{ route('upload') }}',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            enctype: 'multipart/form-data',
            processData: false,
            success: function (data) {
                console.log(data);
            }
        });
        return false;
    });
</script>

6
  • 1
    It's dd in the code or it's like an example here? because is dump and die it will stop at the first loop (file). Commented Jul 28, 2021 at 7:06
  • @JuanEizmendi dd is to check if i am able to get inside loop. Commented Jul 28, 2021 at 7:08
  • 1
    and if you do dd($files), before loop, what's the output? Commented Jul 28, 2021 at 7:13
  • @JuanEizmendi its returning last uploaded file Commented Jul 28, 2021 at 7:14
  • @A.ANoman It is returning last uploaded file Commented Jul 28, 2021 at 7:18

1 Answer 1

1

You have to use like this way

Form name should be like below

<form method="post" id="form_submit" enctype="multipart/form-data">
    @csrf
    ....

    <button type="submit" class="btn btn-success"><i class="fas fa-plus fa-xs"></i>Submit</button>

</form>

$(document).ready(function(){
    $('#form_submit').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url:'{{route('upload')}}',
            method:"POST",
            data:new FormData(this),
            dataType:'JSON',
            contentType: false,
            cache: false,
            processData: false,
            success:function(data){

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

Comments

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.