0
votes

Hello i have a form for image upload

<input type="file" name="ad_image[]">

i want only one image to be required and others to be optional. This is my validation rule and is not working:

'ad_image.*' => 'required|min:1|mimes:png,gif,jpeg,jpg|max:300',

i have tryed this:

'ad_image' => 'required|array|min:1|mimes:png,gif,jpeg,jpg|max:300',

also not working, when i upload jpg file there is error "The ad image must be a file of type: png, gif, jpeg, jpg."

please help with this issue

2

2 Answers

0
votes

You can try:

public function rules()
{
    $rules = [
                'ad_image0'=> 'image|required|mimes:png,gif,jpeg,jpg|max:300'
            ];

    $nbr = count($this->input('ad_image')) - 1;
    foreach(range(0, $nbr) as $index) {
        $rules['ad_image.' . $index] ='image|mimes:png,gif,jpeg,jpg|max:300';
    }

    return $rules;
}
0
votes

I have decided to make my own custom validation rule: This code is in boot method of the AppServiceProvider

public function boot()
{
    Validator::extend('require_one_of_array', function($attribute, $value, $parameters, $validator) {
        if(!is_array($value)){
            return false;
        }

        foreach ($value as $k => $v){
            if(!empty($v)){
                return true;
            }
        }

        return false;
    });
}

The validation message is manualy added as third parameter of the validator

$messages = [
        'require_one_of_array' => 'You need to upload at least one pic.',
    ];

And this is how is used to make sure at lease one image is uploaded (this is in rules array):

'ad_image' => 'require_one_of_array',
'ad_image.*' => 'mimes:jpeg,bmp,png|max:300',