Kneenuts
Kneenuts

Reputation: 11

Laravel validation rules sometimes + required_without

I'm trying to do an update request so some field are not required, 1 of this field in case it is filled has to check that other fields are empty. This is what I have done:

public function rules()
    {
        return [
                'field_a' => ['sometimes', 'nullable', 'required_without_all:field_b,field_c'],
                'field_b' => ['sometimes', 'nullable'],
                'field_c' => ['sometimes', 'nullable'],
               ];
    }

Is there any other way?

Upvotes: 1

Views: 951

Answers (2)

mehdi salimi
mehdi salimi

Reputation: 21

you must do something like this :

$validator = Validator::make($request->all(), [
    "field_a" => [
        "nullable",
        Rule::requiredIf(function () use ($request) {
            if (!$request->field_b && !$request->field_c) {
                return true;
            }
            
            return false;
        })
    ]
]);

Upvotes: 1

PRAMIT PAUL
PRAMIT PAUL

Reputation: 114

you can use required_if, I think it will be more suitable for building up your conditions for validation.

Check the required_if docx for your reference https://laravel.com/docs/8.x/validation#specifying-custom-values-in-language-files

Upvotes: 0

Related Questions