Search code examples
phplaravellaravel-7

Laravel required_if and mimes not working on file input


Code in request file

public function rules()
{
    return [
        'type' =>'required|in:1,2',
        'add' => 'required_if:type,2|in:1,2',
        'image' => 'required_if:add,2|mimes:jpeg,jpg,png,webp|max:10000'
    ];
}

The add attribute select box has 2 option:

  1. Don't upload image
  2. Upload image

On image attribute I did use required_if add attribute has value 2 (i.e. option 2, I want to add image) only then make image field to be a required field and mimes and max file size validation.

But the problem is when option one is selected from add select box which mean I don't want to upload image and then user submit form this throws validation:
The image must be a file of type: jpeg, jpg, png, webp.
As per my validation code it should ignore it as it is required only if option 2 is selected then why this mimes validation error throws up.


Solution

  • I think you can simply add nullable after required_if

    'cover'=>['required_if:can_upload_file,true','nullable','mimes:jpeg,jpg,png','max:5120']