Conditional validator that require a field to be alone

Viewed 35

I would like to accept my update validation on these criteria:

  • firstname and lastname are present and therefore required, but deceased_at is not given
  • or deceased_at is given alone

It makes sense because we could update any field, but when we record the death of someone, we will never change any field value.

    $validator = Validator::make($request->all(), [
        'firstname' => 'required_unless:deceased_at|max:255',
        'lastname' => 'required_unless:deceased_at|max:255',
        'deceased_at' => 'required_without_all:firstname,lastname|date'
    ]);

The required_without_all is cumbersome to use because I have to mention every field. I would prefer something like required_alone.

What is the alternative?

1 Answers

I think you could proceed with an if case as an alternative?

$validator = Validator::make($request->all(), $this->rules($request));

...

protected function rules(Request $request) : array
{
    return $request->has('deceased_at')
        ? ['deceased_at' => 'required|date']
        : [
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
        ]
}
Related