Search code examples
phplaraveldate

How do I write a before-or-equal-date validation that compares to the current date?


I am new to Laravel and am using Laravel 6.x. I need to write a validation that looks at a date supplied by a user on a form (via a JQuery datepicker) to make sure the user chose a date that is on or before the current date. I can't figure out how to express the current date without using apostrophes in my expression somewhere and THAT is going to mess with Laravel understanding the validation properly.

For example, if I write:

'sleep_date' => ['required', 'before-or-equal-date: Date(Y-m-d)']

that's not going to work because there are no apostrophes around the argument of the Date function. But if I add apostrophes as in this example, Laravel says there is a syntax error:

'sleep_date' => ['required', 'before-or-equal-date: Date('Y-m-d')']

How do I code this so that it works as intended?


Solution

  • You can concatenate the current date with a dot:

    'sleep_date' => ['required', 'before_or_equal:' .  Date('Y-m-d')]
    

    Also you can use the laravel now() helper instead Date() in the same way:

    'sleep_date' => ['required', 'before_or_equal:' . now()->format('Y-m-d')]