A
A
Alexander2016-03-09 10:09:54
Laravel
Alexander, 2016-03-09 10:09:54

How to properly validate on a multiupload image?

$data = Request::only('images');
        $rules = [
            'images' => 'required|mimes:png,jpg,jpeg,gif,svg'
        ];
//        dd($data['images']);
        $validator = Validator::make($data, $rules);
        if ($validator->fails()) {
            echo 'false';
        } else {
            echo 'true';
        }
        die();

Pictures output by dd
array:2 [▼
  0 => UploadedFile {#29 ▼
    -test: false
    -originalName: "owner.jpg"
    -mimeType: "image/jpeg"
    -size: 6818
    -error: 0
  }
  1 => UploadedFile {#30 ▼
    -test: false
    -originalName: "port.png"
    -mimeType: "image/png"
    -size: 3710
    -error: 0
  }
]
// они есть , значит форма в html настроенна true

specifically this 'images' => 'required|mimes:png,jpg,jpeg,gif,svg' validator returns `The images field must be one of the following file types: png, jpg, jpeg, gif, svg.`. Tried to add at the beginning of array but same error.
This 'images' => 'image' validator complains about empty `images` field, also tried adding array.
'images' => 'image|array'

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Ernest Faizullin, 2016-03-09
@kentuck1213

$rules = [
    // тут правила для всех полей кроме картинок
];

$validator = Validator::make($request->all(), $rules);

$validator->each('images', ['required', 'mimes:png,jpg,jpeg,gif,svg']);

if ($validator->fails()) {
    // ...
}

and it's better to move the validation to a separate Requests (for example, php artisan make:request ImagesRequest) and describe the rules in app/Http/Requests/ImagesRequest.php
namespace AppHttpRequests;

use AppHttpRequestsRequest;

class ImagesRequest extends Request {

  public function authorize()
  {
      return true; // если гости тоже могут загружать картинки то false
  }

  public function rules()
  {
      return [
        // тут правила для всех полей кроме картинок
      ];
      
      foreach($this->request->file('images') as $key => $val)
      {
        $rules['image.'.$key] = 'required|mimes:png,jpg,jpeg,gif,svg';
      }

      return $rules;

  }
}

and in the controller update and/or store methods change Request to App\Http\Requests\ImagesRequest
public function store(App\Http\Requests\ImagesRequest $request)
{
    // ...
}

I
IceJOKER, 2016-03-09
@IceJOKER

Read documentation!
Validating Arrays

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question