Search code examples
laravellaravel-5laravel-5.4laravel-validation

Laravel 5.4 - exists validation but not required


I have an 'array type' dropdown field in my form, e.g:

<select name="category_id[]">
    <option value="">Please Select</option>
    // more options
</select>

There are 3 of these same fields (hence it being an array type) and they are all optional, but if a value is selected it checks whether it is a valid value as follows:

$rules['category_id'] = 'exists:universities,id';

The problem I'm having is that if the empty option is selected, it is still giving me a validation error, e.g "The selected category is invalid." If I select a valid value I don't get any errors (as expected).

I have tried adding both nullable and sometimes to the validation rule but they don't make any difference. Do I need to do something different with it being an array type field?


Solution

  • If you use "array-like" name for your select, you should use array validation like so:

    $rules['category_id.*'] = ['nullable', 'exists:universities,id'];
    

    But if it's not multi select, you can change the name to category_id to make it work