Skip to content
Advertisement

Laravel collective form, how to upload multiple images?

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!

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement