Search code examples
phplaravellaravel-validation

Laravel validation - required only when two conditions are true


I want purchaser_first_name and purchaser_last_name to be required only when the value of gift input in the request is true and the value of authenticated input is false.

What I have tried so far:

  public function rules()
    {        
        return [
            'gift' => 'required',
             'authenticated'=>required,
             'purchaser_first_name' => 'required_if:gift,true,required_if:authenticated,false',
             'purchaser_last_name' => 'required_if:gift,true,required_if:authenticated,false',

        ];
    }

This approach turns out to use OR operator instead I want the AND operator.


Solution

  • You can try like this:

    'purchaser_first_name' => Rule::requiredIf(function () use ($request) {
        return $request->input('gift') && !$request->input('authenticated');
    }),
    

    In the function, you can set your logic. I'm not sure what you need for real, but it's good for a start.

    Also, check docs for more info about that.