Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve data between two dates in laravel

I am using an eloquent query to retrieve data from a table. The table columns look like this:

id   started_at   finished_at   
1    2016-06-01   2016-06-30  
2    2016-05-03   2016-05-28  

What I want to do is, given a $date (ex: 2016-06-18 ) and get the data of the row, that the $date between started at and finished_at columns.

I have found whereBetween clauses in Laravel documentation, but I do not have an idea to use it correctly.

like image 383
Arunwij Avatar asked Jul 07 '16 16:07

Arunwij


People also ask

How to get data between 2 dates in laravel?

Try to do something like this: $date1 = Carbon::today()->toDateString(); $date2 = Carbon::today()->toDateString(); $myModel = MyModel::find(1); $myModel->whereBetween('created_at', [$date1, $date2]); $myModel->get();

How can I get data between two dates in SQL?

SELECT * FROM ATM WHERE TRANSACTION_TIME BETWEEN '2005-02-28 21:00:00' AND '2008-12-25 00:00:00';

How do I use whereBetween in laravel?

The whereBetween() method is a query builder chained alongside other Laravel query builders used to fetch data from the database. The whereBetween() method queries the database table to fetch rows of records from the database within a range of values.


2 Answers

If you can use Carbon then this code will work fine for you.

$dateS = new Carbon('first day of January 2016');
$dateE = new Carbon('first day of November 2016');
$result = ModelName::whereBetween('created_at', [$dateS->format('Y-m-d')." 00:00:00", $dateE->format('Y-m-d')." 23:59:59"])->get();

Or you can check the issue by debugging query using DB::enableQueryLog(); and DB::getQueryLog(); functions like

DB::enableQueryLog();
$dateS = new Carbon('first day of January 2016');
$dateE = new Carbon('first day of November 2016');
$result = ModelName::whereBetween('created_at', [$dateS->format('Y-m-d')." 00:00:00", $dateE->format('Y-m-d')." 23:59:59"])->get();
var_dump($result, DB::getQueryLog());
like image 86
Brn.Rajoriya Avatar answered Sep 17 '22 17:09

Brn.Rajoriya


Try to do something like this:

$date1 = Carbon::today()->toDateString();
$date2 = Carbon::today()->toDateString();

$myModel = MyModel::find(1);
$myModel->whereBetween('created_at', [$date1, $date2]);
$myModel->get();

Of course, you will need to change the dates.

like image 44
Lucas Mezêncio Avatar answered Sep 21 '22 17:09

Lucas Mezêncio