Petro Bianka
Petro Bianka

Reputation: 145

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.

Upvotes: 1

Views: 7443

Answers (2)

mare96
mare96

Reputation: 3859

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.

Upvotes: 5

vinod
vinod

Reputation: 236

Try to change your validation code as below :

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',
];

Upvotes: 0

Related Questions