Laravel validations with "or" condition

Luís Henriques :

I'm trying to make an input validation in Laravel with a somewhat complex "or" condition.

I need the validator to validate the input (let it pass) if its value is present in a specific table or if its value is "other".

So far, I have:

$validator = Validator::make($data, [

    ...

    'doc_organization' => ['required_with:rb_regist,doctor, exists:user_organizations,full_name'], // TODO: must exist in user_organizations table or be "other"
    'doc_custom_organization' => ['required_if:doc_organization,other', 'max:160'],

    ...

I took a look at Laravel's custom validation rules, conditionally adding rules, and so forth, as well as these posts:

Laravel Validation with or

Validation rules required_if with other condition (Laravel 5.4)

But I can't seem to come up with a custom rule in which I don't query the whole table to know if the name exists (in case it is not "other"). That would make the rule too complex for its purpose.

The other solution I have is to add an entry named "other" in the user_organizations table, which is not ideal.

Am I missing something? How can I make the condition I want without a complex custom validation rule?

Thank you very much.

pr1nc3 :

Since "other" is just a value and not a record in your database you can simply "twist it" a bit to something like:

'doc_organization' => ['nullable|required_with:rb_regist,doctor, exists:user_organizations,full_name'],

The twist is that before your Validator you can have a simple check in your requested value like:

if($request->doc_organization == "other"){
  $request->merge(['doc_organization' => null]);
}

And inject null value to the field inside the request.

Having done that you will comply with "nullable" option which will allow you to pass through.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11535&siteId=1