0
votes

In Laravel, I have a Convention object with year, start_date and end_date. The constrain is that the start_date and end_date fields belong to the year field.

I wanna use a request validation, but none of the available rule seem to correspond to my need.

I would like something like this (but it does not work):

    class ConventionRequest extends FormRequest
    {
      public function rules() {
       return [
         'year' => 'required',
         'start_date' => 'required|date|after_or_equal:year-01-01',
         'end_date' => 'required|date|before_or_equal:year-12-31']
      }
    }
2
You can create custom rule (docs). And use Carbon to check year. - mare96

2 Answers

0
votes

Make a custom Rule:

//YearIsGreater Rule class

public function passes($attribute, $value)
{
    $date = DateTime::createFromFormat("Y-m-d", $value);
    $year = $date->format("Y");

    return $year > request('year');
}

and use it like that

return [
    'year' => 'required',
    'start_date' => [
        'required',
        'date',
        new YearIsGreater,
    ],
    //
],
0
votes

Thanks for your responses. Actually, I succeeded in my initial research direction:

$SameYear = "|after_or_equal:" . $this->year . "-01-01|before_or_equal:" . $this->year . '-12-31'  ;
return [
  'year' => 'required',
  'start_date' => 'required|date' . $SameYear,