How can I validate given time is greater then current time using Carbon on Laravel?
Asked Answered
H

2

6

I wanted to validate time input formatted as H:i:s (e.g. "16:35:00") to be greater than current time.

$request->validate([
  'start_time' => 'required|after:now',
  'end_time' => 'required|after:start_time',
]);

Above code checks the date instead of time.

Haggadist answered 26/5, 2021 at 8:2 Comment(2)
So this is not working? And which format you are sending timeGlori
Its not working and the format is 16:35:00 ( I don't know in H:m:s format )Haggadist
W
4

Change the date to be compared to the actual input using setDateFrom (start in start, end in end) so only time remains checked with what you initially gives as a datetime:

$request->validate([
  'start_time' => 'required|after:' . Carbon::now()->format('H:i:s'),
  'end_time' => 'required|after:start_time',
]);
Wren answered 26/5, 2021 at 8:25 Comment(4)
Its not working it says 'The start time must be a date after 2021-05-26 13:28:06.' but the current time is '17:59:00'Haggadist
I couldn't guess your input format, it would worth to precise it in the question.Wren
In this case it's way much easier, you just need to precise the format for the start: 'required|after:' . Carbon::now()->format('H:i:s'), answer edited.Wren
Actually it works , I had messed up with my time zone :(Haggadist
S
0

However, it won't validate times from different days (eg 09:00 PM - 03:00 AM the next day). start_time and end_time, in this case, should be provided as HH:mm but you can change it easily.

$this->validate($request, [
    'start_time' => 'date_format:H:i',
    'end_time' => 'date_format:H:i|after:start_time',
]);
Summon answered 26/5, 2021 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.