0

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 Answers 2

0

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

hi, this is same as ad_image.*, i want only one of the images to be required. and if you pass image no need to pass mimes rules. thanks for the answer
add a rule $rules['ad_image1']=image|required|mimes:png,gif,jpeg,jpg|max:300 or in the foreach if($index==0) $rules['ad_image'.$index]=image|required|mimes:png,gif,jpeg,jpg|max:300
thanks sam12 i have figured out this variant, but i thing is not sexy, and i have feeling there is better solution
0

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',

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.