Makis
Makis

Reputation: 1244

Get all files in a foreach loop in Laravel

I have some <input type="file"> that are generated dynamically by jQuery. That means that the name attribute of each input is also generated dynamically, is a number and increments by 1 every time a new input appears in the DOM.

I need something like a foreach loop to get all the inputs in my php. I have tried to upload 1 file and i have left 3 inputs empty because my inputs are in a row and i wanted to upload only one image and not 4. i looped through this $all = Input::file(); and the var_dump response is this

NULL object(Symfony\Component\HttpFoundation\File\UploadedFile)#9 (7) { ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> bool(false) ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(10) "index.jpeg" ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(10) "image/jpeg" ["size":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(9408) ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(0) ["pathName":"SplFileInfo":private]=> string(25) "/opt/lampp/temp/phpSVn3Tb" ["fileName":"SplFileInfo":private]=> string(9) "phpSVn3Tb" } NULL NULL

I know that my question is a little bit difficult to understand, but i can not find a better way to explain the problem.

Edit: These are my default inputs:

<div class="row">
<input type="file" name="1">
<input type="file" name="2">
<input type="file" name="3">
<input type="file" name="4">
</div

When the user presses a button, jQuery appends

<div class="row">
<input type="file" name="5">
<input type="file" name="6">
<input type="file" name="7">
<input type="file" name="8">
</div>

and every time the button is pressed, as well

<div class="row">
<input type="file" name="9">
<input type="file" name="10">
<input type="file" name="11">
<input type="file" name="12">
</div

Then in php i need to get all the inputs that have a value.

What i have done is:

$all = Input::all()
foreach ($all as $one => $two) 
   var_dump($two);
}

Upvotes: 1

Views: 7934

Answers (1)

derdida
derdida

Reputation: 14904

You need to create a Form for multiple File uploads:

{!! Form::open(array('url'=>'url_to_controller','method'=>'POST', 'files'=>true)) !!}

And all your files should have a specfic name for the upload, like this:

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

Then you can use your Controller:

class UploadController extends Controller {
   public function store() {

   $files = Input::file('files');

And loop through all files

 foreach($files as $file) {
   ....

Upvotes: 3

Related Questions