MaddGabe's avatar

Dynamic Form Creation with javascript & blade

So I have this code to add new file input on my form dynamically:

    var counter = 1;
    var limit = 10;
    function addInput(divName){
        if (counter == limit)  {
            alert("You have reached the limit of adding " + counter + " inputs");
        }
        else {
            var newdiv = document.createElement('div');
            newdiv.innerHTML = "File" + (counter + 1) + " <br><input name='item_file[]' type='file' />";
            document.getElementById(divName).appendChild(newdiv);
            counter++;
        }
    }

As you may have guessed I'm trying to dynamically upload more files as needed.

It works great with standard html.

But it doesn't work with blade.

If I use the following:

            <div id="dynamicInput">
                <input name='item_file[]' type='file' />
            </div>

Laravel will not recognize the uploaded file. For it to work I need to use:

{!! Form::file('item_file') !!}

But if I do use that I can't dynamically add more file input with javascript.

What can I do to workaround this issue?

0 likes
3 replies
MaddGabe's avatar

Oops, the error was casting the name as an array.

Fixing the code, will get back to you guys.

MaddGabe's avatar

I can now successfully upload multiple files, however I'm stuck on adding the files to the database with eloquent, it only adds a single file, below is my code:

        $files = new Files;

        $myfiles = $req->file('item_file');

        foreach ($myfiles as $file)
        {
            $destinationPath = 'uploads';
            $fileName = $file->getClientOriginalName();
            $files->Filename = $fileName;
            $files->File_Loc = url() . "/uploads/" . $fileName;
        $files->save();
            $upload_sucess = $file->move($destinationPath, $fileName);
        }
MaddGabe's avatar
MaddGabe
OP
Best Answer
Level 1

Solution below: (thanks to wnx_ch on reddit)

        $myfiles = $req->file('item_file');

        foreach ($myfiles as $file)
        {
            $files = new Files;
            $destinationPath = 'uploads';
            $fileName = $file->getClientOriginalName();
            $files->Filename = $fileName;
            $files->File_Loc = url() . "/uploads/" . $fileName;
            $files->save();
            $upload_sucess = $file->move($destinationPath, $fileName);
        }

Please or to participate in this conversation.