简体   繁体   中英

'required_if' validation alongside database check in Laravel 5

I am implementing a survey builder with several allowed question types . These types are:

  1. Single choice
  2. Multiple choice
  3. Star rating

The 1. and 2. require multiple possible answers to be given by a user, whereas the 3. does not require any possible answers at all . These requirements are stored as true / false values in question_types.multiple_answers column.

I need a validation rule, that will:

require answers[] array to be present in the request, only if the selected question_type's corresponding multiple_answers value is set to true in the database .


Here is an illustration of what I'm trying to achieve:

...->validate($request, [
    'answers' => 'require_if:type,...' // <-- if 'type' has 'multiple_answers' set to true in database
]);

You can create conditional validation rules to do what you want. The rule specified as the second parameter will only be evaluated if the function specified as the third parameter returns true.

$v->sometimes('answers', 'required', function($input) {
    // check database and return true if multiple_answers is set for the type ($input->type)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM