Search code examples
laravellaravel-5.3laravel-validation

Apply a particular validation rule on a specific input, only if another input is also present and set to a specific value


To put it simply, what I want to do is to check if the value of a particular input exists in the database, but I want the exists rule to be applied only if another input is also present with a specific value.

For example, let’s say I have a form with a select named type and a text field named id.

<select name="type">
    <option value="0">Type0</option>
    <option value="1">Type1</option>
</select>

<input type="text" name="id">

If the type is present and equals to 1 I want to check if the id input exists in the database table users, otherwise the exists rule to not be applied at all, while the rest of the validation rule to be applied as normal.

Edit:

Preferably, I'd like to use a form request for doing the validation. Can that be achieved using a form request?


Solution

  • You can conditionally add rules as:

    $v = Validator::make(...);
    
    $v->sometimes('id', 'exists:table,column', function($input) {
         return $input->get('type') == 1;
    });
    

    Update

    For form request you can do as:

    $rules = [
        ...,
    ];
    
    if ($this->get('type') == 1){
        if (isset($rules['id'])){
            $rules['id'] .= '|exists:table,column';
        }
        else {
            $rules['id'] = 'exists:table,column';
        }
    }
    
    return $rules;