Uploading Multiple Files

Just decided to share a solution for uploading multiple files via Laravel as i have spent some time today on researching on why my code doesn’t work when I am doing everything mentioned in the Laravel API. The problem was that the “multiple” attribute of the file input is not enough to trigger sending an array of files to the controller.

So my solution is below. Of course this is far from a good one, but I decided to post it as i spent about 3 hours reading about different types of errors and why they should be happening as well as different solutions in order to find out I need this simple “[ ]” added at the end of the name attribute value.

I will constantly improve this with adding code for validating the form as well as other stuff so bear with me.

View:

@extends(‘layouts.default’)
@section(‘content’)
<h1>Adding product image(s)</h1>
{{ Form::open([‘route’ => ‘products.store’, ‘files’ => true]) }}

<div class=”form_row”>
{{ Form::label(‘prod_img[]’, ‘Product Pictures: ‘); }}
{{ Form::file(‘prod_img[]’, [‘multiple’]); }}
{{ $errors->first(‘prod_img’); }}
</div>

{{ Form::submit(‘Add product’); }}
{{ Form::close() }}
@stop

Controller:

inside of the controller class I have

public function store()
{

//path to the project folder you want to put your images

$path = public_path() . “\assets\images\products\\”;
File::makeDirectory($path);

//getting the images to upload

$files = Input::file(‘prod_img’);

foreach($files as $file)
{
$fileName = $file->getClientOriginalName();
$file->move($path, $fileName);
}

return Redirect::route(‘products.index’);

}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>