Search code examples
phplaravellaravel-5laravel-validation

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?


Solution

  • 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!