1

I currently have validation in the validation request:

public function rules()
{
    $rule['name'] = "required";
    $rule['provider'] = "required";

    switch ($this->provider) {
        case 'cloudName1':
            $rule['api_key'] = "required";
            break;
        case 'cloudName2':
            $rule['key'] = "required";
            $rule['secret'] = "required";
            break;
    }

    return $rule;
}

Is there Laravel rule I can use instead of using switch() condition to do same thing?

1 Answer 1

3

UPDATED:

You can use Laravel's required_if rule -

required_if:anotherField,value,...

The field under validation must be present and not empty if the anotherfield field is equal to any value.

This is how you can implement it into your code:

$rule[
    'name' => 'required',
    'provider' => 'required',
    'api_key' => 'required_if:provider,cloudName1',
    'key' => 'required_if:provider,cloudName2',
    'secret' => 'required_if:provider,cloudName2',
];

See Laravel Validation Docs

Hope this helps!

Sign up to request clarification or add additional context in comments.

5 Comments

Updated my answer!
You didnt use anotherfield for required_with - you just used value?
See my updated answer, I think this would work, sorry for inconvenience!
I don't think your answer is correct. key and secret is required when provider value is cloudName2 for example
I've updated the answer, please use required_if, check it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.