How do I make one of the several fields required?

php laravel validation laravel-validation

82 观看

2回复

115 作者的声誉

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?

作者: Benedict 的来源 发布者: 2017 年 12 月 27 日

回应 2


3

106023 作者的声誉

决定

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;
}
作者: Alexey Mezenin 发布者: 2017 年 12 月 27 日

3

5073 作者的声誉

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;
作者: Tpojka 发布者: 2017 年 12 月 27 日
32x32