Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pllaguno's avatar

custom date validation

Hi, i have a API call which i recieve 2 query parameters, start_date and end_date. I want to validate that the time between the two dates is less than 5 days, is there a way to do this?

$validatedData = $request->validate([
            'date_start' => 'required|date',
            'date_end' => 'required|date|after_or_equal:date_start',
        ]);
      ```
0 likes
5 replies
pllaguno's avatar

I think that can do the trick. something like this, just that i am unsure how to add that to the existing date_end validation rules, as in the example it is done different syntax.

$validatedData = $request->validate([
            'date_start' => 'required|date',
            'date_end' => 'required|date|after_or_equal:date_start',
            function ($attribute, $value, $fail){
                $start = Carbon::parse($request->get('date_start'));
                $end = Carbon::parse($request->get('date_end'));
                if($end->diffInDays($start)>1){
                    $fail($attribute.' date range is bigger than 1 day.');
                }
            }
        ]);
pllaguno's avatar

Changed it to this:

$validatedData = $request->validate([
            'date_start' => 'required|date',
            'date_end' => ['required','date','after_or_equal:date_start',
                function ($attribute, $value, $fail){
                $start = Carbon::parse($request->get('date_start'));
                $end = Carbon::parse($value);
                if($end->diffInDays($start)>1){
                    $fail($attribute.' date range is bigger than 1 day.');
                }
            }],
            
        ]);

the problem is that i get an eror since $request->get('date_start' does not exist

Cronix's avatar
Cronix
Best Answer
Level 67

You need to pass $request to the closure, and just use $request->date_start instead of $request->get(), unless it's a GET request.

function ($attribute, $value, $fail) use ($request) {
    $start = Carbon::parse($request->date_start);
1 like
pllaguno's avatar

Thanks! didn't know about that syntax to pass on a variable.

Please or to participate in this conversation.