Skip to content
Advertisement

How to use required_if on file array fields with an array for first argument?

I have an with an array of image_file (image_file[1], image_file[2]). They are input of type file. This images are required only if another array of fields (proposition_type) is defined on 2.

For example :

  • if proposition_type[1] == 2, image_file[1] has to be filled ;
  • if proposition_type[2] == 1, image_file[2] has not to be filled.

I have tried to use the following rules :

$rules = [
    (...)
    'image_file.*' => 'required_if:proposition_type.*,2|image',
];

But any error on image_file fields is raised.

Moreover, I have used the required validator on my image_file.* and, here again, no error is raised.

Maybe someone has a solution for this? Or maybe am I doing something wrong? 🙂

Thanks!

Advertisement

Answer

So what I did finally was to generate (complete, to be precise) my rules array on the fly, by making a while, and adding an array entry for each images.

$i = 1;
$total_images = count($image_array);
while ($i <= $image_array)
{
    $this->rules['image_file.'.$i] = 'nullable|required_if:proposition_type.'.$i.',2|image';
    $i++;
}

This, of course, need your form to have inputs with image_file1, image_file2, … names.

Hope it will help others!

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement