2

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.

Dilhan Nakandala
  • 301
  • 5
  • 24
Reuben Wedson
  • 69
  • 2
  • 10

1 Answers1

1

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.');
            }
        });
    }
}
Reuben Wedson
  • 69
  • 2
  • 10
Kurt Friars
  • 3,625
  • 2
  • 16
  • 29