Peter Griffin
Peter Griffin

Reputation: 300

Laravel 5 validation append to rule

I'm using Laravel 5.4 and I have 2 date fields. The first is required and the second is optional.

I'm having problems with the validation when the second date field is empty.

I understand why but only want to run the before_or_equal rule if the second date is not empty

$this->validate($request, [
    'start_date' => 'required|date|before_or_equal:end_date',
    'end_date' => 'nullable|bail|date|after_or_equal:start_date',
]);

How can I update my code ignore the rule if the date field is empty?

I did think about this

if($request->has('end_date')) {
    //do something
}

The only other option is to create a custom validation rule and compare the dates

Upvotes: 0

Views: 1190

Answers (2)

Raza Mehdi
Raza Mehdi

Reputation: 941

I would do it like this:

$rules = [
    'start_date' => 'required|date|before_or_equal:end_date',
];

if ($request->get('end_date') != '') {
    $rules['end_date'] = 'required|date|after_or_equal:start_date';
}

$this->validate($request, $rules); 

Upvotes: 0

Niklesh Raut
Niklesh Raut

Reputation: 34914

No need to put both condition remove |before_or_equal:end_date from start_date. Only after_or_equal:start_date would work

Use required_with:foo,bar,...

Try like this

$this->validate($request, [
    'start_date' => 'required|date',
    'end_date' => 'required_with:start_date|nullable|bail|date|after_or_equal:start_date',
]);

Upvotes: 1

Related Questions