Search code examples
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

    • If the "avatar" field may not be present in the input array you want to use:

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


    • If the "avatar" field will absolutely be in the input array and it's value will be then null you want to use:

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