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?

1

2 Answers 2

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 .

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

6 Comments

I tried to add additional_files[] but with no luck :-/
No, I don't get any errors... I suspect there is something wrong with hasFile or the foreach-loop
Have you tried adding the $request->file('additional_files) inside foreach function without converting it into variable ? Try it and let me know
I tried to do dd(request()->file('additional_files')) and it returns null even when I tried to upload files
in your js file , add the same method : if (additional_files[].length > 0) { formData.append("additional_files[]", additional_files[]); }
|
0

this will give you all the files in the request

$files = collect($request->allFiles())->flatten()->toArray();

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.