Reuben Wedson
Reuben Wedson

Reputation: 69

Laravel 5.7 validation using required_with and required_with_all for 3 fields does not work

My question is how does logics using required_with and required_with_all for Laravel validation works?

I have read the documentation but can not get anything from it documentation link

I am applying for 3 different fields

Let me give you my example now to get what I want

'start' => 'nullable|required_with:end',
'end' => 'nullable|required_with:start',
'repeat' => 'nullable|required_with_all:start,end',

if I just submit with only repeat field no validation is performed in Laravel.

You can remove nullable is from the code I copied from, still no validation is performed if you provide only repeat field.

Upvotes: 2

Views: 851

Answers (1)

Kurt Friars
Kurt Friars

Reputation: 3764

What OP actually wanted here is:

  1. Being able to submit start and end without repeat being present
  2. Start and end are required together
  3. Not being able to submit repeat if start or end are present
use Illuminate\Validation\Validator;

class MyFormRequest extends FormRequest
    ...

    public function rules()
    {
        return [
          'start' => 'required_with:end|required_without:repeat',
          'end' => 'required_with:start|required_without:repeat',
          'repeat' => 'required_without_all:start,end',
        ];
    }

    public function withValidator(Validator $validator)
    {
        $validator->after(function ($validator) {
            if ((!$this->input('start') || !$this->input('end')) && $this->input('repeat')) {
                $validator->errors()->add('repeat', 'The repeat field is required when start and end are present.');
            }
        });
    }
}

Upvotes: 1

Related Questions