Sven van den Boogaart
Sven van den Boogaart

Reputation: 12327

Laravel 5 upload multiple image validation

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?

Upvotes: 3

Views: 2370

Answers (2)

ujwal dhakal
ujwal dhakal

Reputation: 2469

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

Upvotes: -1

Mete Kabak
Mete Kabak

Reputation: 332

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

Upvotes: 2

Related Questions