Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make one of the several fields required?

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?

like image 273
Benedict Avatar asked Dec 27 '17 17:12

Benedict


People also ask

How do you set a field as required?

Select the field that you want to require always has a value. In the Field Properties pane, on the General tab, set the Required property to Yes.

What does it mean the field is required?

When you make a field required, people must enter an answer to the field in order to submit their entry. When someone tries to submit an entry without filling out a required field, we highlight the problematic fields and display an error message to let them know the field is required.


1 Answers

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;
}
like image 102
Alexey Mezenin Avatar answered Nov 15 '22 03:11

Alexey Mezenin