Alexander Lomia Alexander Lomia - 1 year ago 64
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
values in

I need a validation rule, that will:

array to be present in the request, only if the selected
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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download