3

I am trying to upload multiple images at once. The files are being uploaded but they pass the validation even if they are not a valid iamge. I want to upload all valid files and return a message with the ammount of files that werent uploaded succesful.

My function:

public function addImages($id, Request$request)
{
    $files = Input::file('images');
    $uploaded = 0;
    $failed = 0;
    foreach ($files as $file) {

        // Validate each file
        $rules = array('file' => 'required|image');
        $validator = Validator::make(array('file'=> $file), $rules);

        if($validator->passes()) {
            $destinationPath = 'uploads';
            $filename = $file->getClientOriginalName();
            $upload_success = $file->move($destinationPath, $filename);
            if($upload_success){
                $uploaded ++;
            }
            else {
               $failed ++;
            }
        } else {
            $failed ++;
        }
    }
    \Session::flash('success_message',$uploaded.' files uploaded.');
    if($failed > 0){
        \Session::flash('errors','Some files werent valid.');
    }
    return redirect('admin/myroute/'.$id);
}

For some reason if I upload files withhout any extension they are still uploaded. What am I doing wrong?

2 Answers 2

2

You should not validate it in controller, You should use each method for it, example in Your Request file.

protected function getValidatorInstance()
{
    $validator = parent::getValidatorInstance();


    $validator->each('files', ['image']);

    return $validator;
}

This simply checks all the files.

more information,

Laravel API about validation

Sign up to request clarification or add additional context in comments.

Comments

-1

if your taking about validation you should specify like file types you can specify the the name and make a validation like this 'image' => 'mimes:jpeg,jpg,bmp,png' . Hope this would help

4 Comments

image is the input field name and mimes is the validation
image is also a validation rule, and it uses mimes:jpeg,jpg,png,bmp by default.
i know but in the code given by me image means the input name :) and giving the mimes validation :) may be we both are misunderstanding nm :)
I know, the problem is you don't need to use mimes instead of image that asked on the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.