For a laravel project im trying to upload multiple files. The files are optional so I want to do a check before I loop through all the images.
My form input part.
{!! Form::open(array( 'files'=>true)) !!}
{!! Form::file('images[]', array('multiple'=>true, 'class' => 'form-control')) !!}
{!! Form::close() !!}
(the form has enctype="multipart/form-data" and the input field has multiple="1")
My current code for checking:
$files = Input::file('images');
$uploaded = 0;
$failed = 0;
if(!empty($files)){
try {
foreach ($files as $file) {
//upload file $uploaded ++ or $failed ++;
$rules = array('file' => 'required|image'); // 'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(array('file' => $file), $rules);
if ($validator->passes()) {
//if file uploaded succesfuly $uploaded++;
}
else{
$failed++;
}
}
}
catch(Exception e){
//Handle error
}
}
When i change !empty($files) with if(count($files) > 0) it still goes in the foreach.
I use $failed and $uploaded, after this part of code is finished, to show a message depending on the ammount of failed/uploaded. However when I dont select any file $failed is 1 (even if array is empty). Looping the $files to count the ammount, before I loop them to upload feels like a waste of memory/time/etc, is there a better way than looping the $files array to get the ammount of files?
Subquestion: Why is it running the foreach loop when it's empty?
$failed is 1 (even if array is empty)? - u_mulder