Alexander Lomia Alexander Lomia - 4 months ago 11
PHP Question

'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
]);

Answer

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)
});