Search code examples
laravelvalidationlaravel-7laravel-validation

How to add validation for field accept number and null? [Laravel 7.x]


I want to store the score value as a number when is_pass is true. If is_pass is false then score should be null. So I added validation like below for score

'score' => 'required_if:is_pass,true|numeric'

But I have an issue when is_pass is false then also it's expected score value as numeric. How to solve this issue? Is there any diffrent option is there other than custom validation? I am using laravel 7.


Solution

  • You should define a variable to keep you rules. Then base on condition change your rules.

    if((bool) $request->is_pass === true)
        $rules['score'] = 'required_if:is_pass,true|numeric';
    else
        $rules['score'] = 'required_if:is_pass,false|null';