I'll-Be-Back
I'll-Be-Back

Reputation: 10828

Laravel Validation using rule?

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?

Upvotes: 1

Views: 104

Answers (1)

Saumya Rastogi
Saumya Rastogi

Reputation: 13699

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!

Upvotes: 3

Related Questions