How to make one of several fields?

My Eloquent model consists of 30 fields.

Validation Rule:

  • First field required
  • Of the other 29 fields, at least one field is required.

While checking the Laravel 5.5 documentation, I found the validation rule to required_without_allbe quite relevant. One way to write the aforementioned validation rule would be to indicate in each of the 29 fields required_without_all:field1,.....,field28(i.e., Other fields, excluding the first and specified field)

But for this you need to write 28 field names in the check rule for all fields except the first. Is there a simpler, not redundant approach?

+6
source share
2 answers

required_without_all, , - Request:

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;
}
+3

$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()) {
    //
}

Rule() - :

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

return false;
+3

All Articles