How do I make one of the several fields required?
Asked Answered
C

2

6

My Eloquent model consists of 30 fields.

Validation Rule:

  1. The first field is required
  2. Out of the other 29 fields, at least one field is required.

Checking the documentation of Laravel 5.5, I found required_without_all validation rule quite relatable. One way of writing the above validation rule would be to specify in each of the 29 fields required_without_all:field1,.....,field28 (i.e. the other fields excluding the first and the given field)

But, this requires writing the 28 field names in the validation rule of all the fields excluding the first one. Is there any simpler, non-redundant approach?

Chromatophore answered 27/12, 2017 at 17:37 Comment(0)
M
3

You can still use required_without_all, but to keep it maintainable, you could do something like this in related Request class:

public function rules()
{
    $rules = [
        'name' => 'required',
        'email' => 'required|email'
    ];

    $fields = collect(['field1', 'field2', ...., 'field29']);

    foreach ($fields as $field) {
        $rules[$field] = 'required_without_all:' . implode(',', $fields->whereNotIn(null, [$field])->toArray());
    }

    return $rules;
}
Marathon answered 27/12, 2017 at 18:6 Comment(1)
While the above code worked, I made a slight change to it as I have some more rules for the other 29 fields. I changed this line to $rules[$field].= '|required_without_all:' . implode(',', $fields->whereNotIn(null, [$field])->toArray()); After the change, it is not working any more. My rules for these fields are 'sometimes|date_format:Y-m-d' Is it in relation with the something rule?Chromatophore
D
3

Use after validation hook

$validator = Validator::make($request->all(), [
    'field1' => 'required',
]);

$validator->after(function ($validator) {
    if ( !$this->additionalRule()) {
        $validator->errors()->add('field2', 'At least one additional field has to be set!');
    }
});

if ($validator->fails()) {
    //
}

In additionalRule() method you can put something like:

if (isset($field2, field3,...field29)) {// at least one field is set
    return !empty($field2 || field3 || ... || field29);
}

return false;
Dine answered 27/12, 2017 at 18:13 Comment(4)
Where should the additionalRule() method be defined?Chromatophore
If you don't use custom request class, then in controller. You can make it as protected or private.Dine
I've defined the method in the controller itself. So, how can you directly use $field1, $field2, it throws an error that $field1.....are undefined?Chromatophore
Pass Request $request instance as argument.Dine

© 2022 - 2024 — McMap. All rights reserved.