0

How would I run a validator for every image thats in a request, when the form file names are always different.

My form file names can range from file1 all the way to section_1_image[0][].

I need to create a validation that I can paste in every controller, that checks the post request and validates ALL files if it has them

This is what I have so far

    $validator = Validator::make($request->all(), [
        'items' => 'array',
    ]);

    $validator->each('items', [
        '*'       => 'max:50'
    ]);

    if ($validator->fails()) {
        echo 'Error';
        exit;
    }

But this doesn't seem to do anything, it just gets ignored?

S_R
  • 1,818
  • 4
  • 27
  • 63
  • Did you tried my answer? Or you got any other method? – iamab.in May 18 '18 at 13:51
  • @ab_ab Apologies, It didn't work, I tried multiple other methods so I ended up completing my task via JS, and validating every image in the form before submitting. – S_R May 21 '18 at 07:41
  • You got any error? or something else happened? If you are interested in server side validation we can fix it. It would be helpful for other people with same requirements. I was tested my answer in my conditions. – iamab.in May 21 '18 at 10:41
  • No error, it just allowed the picture to be processed – S_R May 21 '18 at 11:40
  • where do you write this? in a controller or else somewhere? can you put a `dd($rule)` right after the loop and show the result here? – iamab.in May 21 '18 at 11:48

2 Answers2

0

I would advise you to change all your files name to something like files[ file_name]

<input type="file" name="files[first]">
<input type="file" name="files[section_1_image]">

So that in each controller you have

$validator = Validator::make($request->all(), [
    ...
    'files.*' => 'file_rules...',
]);
Ramy Herrira
  • 574
  • 10
  • 13
0

A custom rule array is build with the file names that are present in the request and the request is validated against it.

use Illuminate\Support\Facades\Input;

//code

$rule = [];

foreach (Input::file() as $key => $value) {
    $rule = $rule + [$key => 'max:50'];
}

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

if ($validator->fails()) {
    //validation failed
    //custom error message common for all file(optional)
    $validator->errors()->add('image_size_error', 'Images size exceeds!');

    return redirect()
                ->back()
                ->withErrors($validator)
                ->withInput();
}

Hope it helps..

iamab.in
  • 2,022
  • 3
  • 18
  • 39