DEV Community

Cover image for Laravel Get Data Between Two Dates Tutorial
Sonagra Bhavesh
Sonagra Bhavesh

Posted on

Laravel Get Data Between Two Dates Tutorial

Hi Guys,

In this article let's see example of how to get data between two dates in laravel example. This is a short guide on laravel get data between two dates. Here you will learn get data between two dates laravel. We will utilizes get data between two dates in laravel. Let's get started with get data between two dates in laravel.

more..

https://codingtracker.blogspot.com/2021/06/laravel-get-data-between-two-dates.html

Top comments (1)

Collapse
 
nicolus profile image
Nicolas Bailly • Edited

Hi,

Thanks for the tutorial, unfortunately it's a bit misleading because that's not how Carbon (or DateTime) works. Your examples would not work as expected for items created on the last or first day of the date range. if we take your first example :

$startDate = Carbon::createFromFormat('d/m/Y', '01/06/2021');
$endDate = Carbon::createFromFormat('d/m/Y', '31/05/2021');

$posts = Post::whereBetween('created_at', [$startDate, $endDate])->get();                        
Enter fullscreen mode Exit fullscreen mode

It looks like we want to retrieve all articles written between January and May. But here $startDate and $endDate will have both a date and a time (the time being whatever time it is right now, when running the script). since created_at is a Datetime column, it also has a time. So you're not comparing dates but Datetimes.

So if an article was written on May 31th at 10:05 (2021-05-31 10:05:00) and you run the script at 11:00 it won't be returned (but if you run the script at 09:00 it will).

Similarly if you have an article written on Jeanuary 1st at 10:05 and you run the script before 10:05 it won't be returned.

This actually prompted me to write a full post to explain some solutions :