Javed
Javed

Reputation: 857

Laravel Validation- check depend input value

In my validation function, some fields is related to other fields input value. So how can I validate it.

For example : Here is my validation function

 public static function validate($data) {
    return [
        'firstname'               => 'required',
        'local_or_expat'          => 'required',
    ];
}

So here if the local_or_expat value is expat, then there is another field country which is mandatory.

How can I do that?

Upvotes: 0

Views: 1342

Answers (2)

Hafez Divandari
Hafez Divandari

Reputation: 9049

You may use required_if like this:

return [
    'firstname' => 'required',
    'local_or_expat' => 'required|in:local,expat',
    'country' => 'required_if:local_or_expat,expat',
];

See Laravel docs for more info.

Upvotes: 2

zahid hasan emon
zahid hasan emon

Reputation: 6233

you can use required_if rule for this.

public static function validate($data) {
    return [
        'firstname' => 'required',
        'local_or_expat' => 'required',
        'country' => 'required_if:local_or_expat,==,expat'
    ];
}

this rule means if local_or_expat value is expat then country is required too. you can use Rule class too.

use Illuminate\Validation\Rule;

public static function validate($data) {
    return [
        'firstname' => 'required',
        'local_or_expat' => 'required',
        'country' => Rule::requiredIf($request->local_or_expat == 'expat'),
    ];
}

Upvotes: 0

Related Questions