phplaravellaravel-5laravel-5.3

Laravel validation for field if "image/file" is selected?


I have a field "image", type is file and need only to validate if image is selected, means it can be also empty.

I tried it so: 'avatar' => 'mimes:jpeg,jpg,png,gif|max:100000', but so it is also required.

I tried still with parameters present and sometimes but the field is still required.

How can I validate it only if image is selected?


Solution

  • 'avatar' => 'sometimes|mimes:jpeg,jpg,png,gif|max:100000'

    In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule.


    'avatar' => 'nullable|mimes:jpeg,jpg,png,gif|max:100000'

    The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values. To quickly accomplish this, add the nullable rule.