4

I wan't to change my form to enable more than one image to be uploaded at a time, this is what I currently have,

part of my form:

{!! Form::open(['action' => 'PostsController@store', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}

{{Form::file('stock_image')}}

my controller:

if($request->hasFile('stock_image')){
        $filenameWithExt = $request->file('stock_image')->getClientOriginalName();
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        $extension = $request->file('stock_image')->getClientOriginalExtension();
        $fileNameToStore= $filename.'_'.time().'.'.$extension;
        $path = $request->file('stock_image')->storeAs('public/images', $fileNameToStore);
    } else {
        $fileNameToStore = 'noimage.jpg';
    }

thanks for your help!

2 Answers2

4

For the file helper you should use unescaped rendering:

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

If you want to upload multiple files you just have to use multiple input fields.

{!! Form::file('stock_image_1') !!}
{!! Form::file('stock_image_2') !!}
{!! Form::file('stock_image_3') !!}

If you want them in an array you can use the following syntax:

{!! Form::file('stock_image[]') !!}
{!! Form::file('stock_image[]') !!}
{!! Form::file('stock_image[]') !!}

If you want to process the last one you can do the following:

An other tip: You can use the 'files' => true option for the Form::open() method instead of manually setting the enctype. It's a helper option.

Mark Walet
  • 1,147
  • 10
  • 21
  • Ok thanks! So in the controller would I have to copy the lot and change it to 'stock_image_2' and so on or could I include it all in one? (I'm very new to back-end) thanks –  Sep 11 '17 at 19:16
  • If you use the second option. with the square brackets. You get an array of files when you type `$request->file('stock_image`);` (Note: I would change the name to `stock_images` if you do it this way.) – Mark Walet Sep 11 '17 at 19:23
  • This approach breaks DRY concept. Also you need to change your code if you want to upload more files later. There are better approach - use `multiple` attribute. See my answer – Yaroslav Jan 17 '21 at 17:34
1

You can just set multiple attribute for file input so user be able to select multiple files at once e.g.

{!! Form::file('stock_image[]', ['multiple' => true]) !!}

and than get your stock_image from the input, check if it's array and place your file saving code block into foreach

Don't forget to name your file input with [] in the end

Yaroslav
  • 2,338
  • 26
  • 37