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

nanadjei2's avatar

Retrieve data within a date range.

I am trying to fetch data between a date range.

For example; When the user selects 13/11/2020 from the calendar as a from_date and goes ahead to select 13/11/2020 as a to_date the below code works.

But if the date user selects a different time date range, eg; 13/08/2020 from the calendar as a from_date and 12/11/2020 from the calendar as a to_date no data is received even though I have data for the selected time range in my database.

    $response = $sales->with('product')
        ->whereDate('created_at', '<=', $request->from)
        ->whereDate('created_at', '>=', $request->to)
        ->get();

The below code is also able to fetch data in a different date range and not the same date. Eg; from: 13/07/2020 to: 13/09/2020... works but not from:13/07/2020 to:13/07/2020

 $response = $sales->with('product')->whereBetween('created_at', [$request->from, $request->to])->get();

Hope someone helps me out... Thank you

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

Your comparators are the wrong way around?


$response = $sales->with('product')
        ->whereDate('created_at', '>=', $request->from)
        ->whereDate('created_at', '<=', $request->to)
        ->get();

Where between does not work because both start and end are 13/07/20 00:00:00

you can fix this by adding 1 day to the end date

 $response = $sales->with('product')
        ->whereBetween('created_at', [
               $request->from, 
               Carbon::parse($request->to)->addDay()
           ])
        ->get();
1 like
nanadjei2's avatar

aaaahh haha no wonder you are smiling at me in your profile pic. Thank you

Please or to participate in this conversation.