Search code examples
phplaravellaravel-5laravel-validation

Laravel Validation depending on the value of field


Let's say I have a combo box with some values

<option value="0">All</option>
<option value="1">ABC</option>
<option value="2">PQR</option>
<option value="3">XYZ</option>

My validation is as follows

'dept_id' => 'required|exists:department,id'

As you can see I want the dept_id field to be the id that exists in department table id column but my first option is "All" whose id obviously does not exists in department table.

So how can I ignore the exists rule if value=0 in Laravel 5.6 ?


Solution

  • you have 2 ways either create a custom validation rule,

    or have the HTML like this

    <option>All</option>
    <option value="1">ABC</option>
    <option value="2">PQR</option>
    <option value="3">XYZ</option>
    

    and remove the required rule.

    I recommend the custom validation rule way, an example would be like this

    $validator = Validator::make($request->all(), [
        'dept_id' => [
            'required',
            function($attribute, $value, $fail) {
                if ($value != '0') {
                   // check the existence of $value in db 
                   // if exists return true
    
                }
                // return error because it was neither found in db  nor its All
                return $fail($attribute.' is invalid.');
            },
        ],
    ]);
    
    $validatior->validate();