1

I have a <form> where it is possible to upload multiple files. The multiple files should be stored in a different table but for some reason the files are not stored in the database.

Here is the form:

<form method="POST" action="{{ route('application.store') }}" id="form" enctype="multipart/form-data">
   <input name="name" type="text" />
   <input name="email" type="text" />
   <input name="phone" type="text" />
   <input name="additional_files" type="file" multiple />
</form>

Then in my controller I have this:

public function store()
{
    $validator = Validator::make(
        request()->all(),
        [
            'email' => ['required', 'email'],
            'name' => ['required', 'string'],
            'phone' => ['required', 'string']
        ],

    );

    if ($validator->fails()) {
        return response()
            ->json($validator->messages(), 400);
    }


    $application = Application::create([
        'email' => request()->email,
        'name' => request()->name,
        'phone' => request()->phone,
    ]);

    if (request()->hasFile('additional_files')) {
        $files = request()->file('additional_files');
        foreach ($files as $file) {

            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $filesize = $file->getSize();

            $path = Storage::disk('local')->put('attachments', request()->file($filename));
            $attachment_file = ApplicationFile::create([
                'files_id' => $application->id,
                'application_id' => $application->id,
                'attachment' => $path,
                'attachment_name' => $extension,
                'attachment_size' => $filesize,
            ]);

            new ApplicationFile($attachment_file);
        }
    }
}

My model for the files looks like this:

class SingleApplicationFile extends Model {
    protected $table = "additional_files";

    protected $fillable = [
        'attachment', 'files_id', 'attachment_name', 
        'attachment_size', 'application_id'
    ];

    public function files()
    {
       return $this->belongsTo('App\Application');
    }
}

Then it gets posted with JS:

var additional_files = [];

$("#form input[name='additional_files']").change(
    function() {
        additional_files = [];
        for (var i = 0; i < $(this)[0].files.length; i++) {
            additional_files.push($(this)[0].files[i]);
        }
    }
);

$('#form button[type="submit"]').click(function(e) {
    e.preventDefault();

    var formData = new FormData();

    formData.append(
        "name",
        $("#form")
            .find('input[name="name"]')
            .val()
    );
    formData.append(
        "email",
        $("#form")
            .find('input[name="email"]')
            .val()
    );

    formData.append(
        "phone",
        $("#form")
            .find('input[name="phone"]')
            .val()
    );

    if (additional_files.length > 0) {
        formData.append("additional_files", additional_files);
    }

        axios
            .post($("#form").attr("action"), formData)
            .then(response => {
              // some success message
              }
            })
            .catch(error => {
                console.log("ERR: ", error);
            });

 });

The "regular" fields get stored like they should, but the uploaded files don't stored and when I do dd($request()->all()) it returns:

additional_files: [object File], [object File] // for each file

I have no clue what I'm doing wrong. I tried to add additional_files[] on the input -> <input type="file" name="additional_files[]" /> but with no luck.

Can someone help me out?

ST80
  • 3,565
  • 16
  • 64
  • 124
  • 1
    Possible duplicate of [Multiple file upload in php](https://stackoverflow.com/questions/2704314/multiple-file-upload-in-php) – fonini Sep 24 '19 at 12:24

2 Answers2

0

You are missing to send the multiple files from view page . You should use [] this in your input type .

<input name="additional_files[]" type="file" multiple />

After this only the files will gets uploaded as an array . Then you can able to traverse through the array, then you can able to do other things. Let me know if any issues you got .

farooq
  • 1,603
  • 2
  • 17
  • 33
  • I tried to add `additional_files[]` but with no luck :-/ – ST80 Sep 24 '19 at 12:59
  • No, I don't get any errors... I suspect there is something wrong with `hasFile` or the `foreach`-loop – ST80 Sep 25 '19 at 07:13
  • Have you tried adding the `$request->file('additional_files)` inside `foreach` function without converting it into variable ? Try it and let me know – farooq Sep 25 '19 at 07:22
  • I tried to do `dd(request()->file('additional_files'))` and it returns `null` even when I tried to upload files – ST80 Sep 25 '19 at 07:30
  • in your js file , add the same method : `if (additional_files[].length > 0) { formData.append("additional_files[]", additional_files[]); }` – farooq Sep 25 '19 at 07:41
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/199943/discussion-between-farooq-and-st80). – farooq Sep 25 '19 at 08:06
0

this will give you all the files in the request

$files = collect($request->allFiles())->flatten()->toArray();
Ahmed Aboud
  • 1,232
  • 16
  • 19