user8625625
user8625625

Reputation:

How to search for an entry by comparing two dates in Laravel?

I have a table with a column varchar "date_start" and a column varchar "date_end".

Here's an example of a date stored inside :

2016-01-05 00:00:00

I would like to collect all the elements between two dates. I tried this, but it does not work:

$dateStart = $request->get('date_start'); // Return 1990-01-01
$dateEnd = $request->get('date_end'); // Return 2017-12-06

$query = Event::published();

if ($dateStart != '') { $query->where('date_start', '<=', $dateStart); };
if ($dateEnd != '') { $query->where('date_end', '>=', $dateEnd); };

$items = $query->get();

The returned query :

select * from `events` where `status` = 'PUBLIÉE' and `date_start` <= '1990-01-01' and `date_end` >= '2017-12-06' order by `updated_at` desc`

Upvotes: 0

Views: 38

Answers (1)

Sapnesh Naik
Sapnesh Naik

Reputation: 11636

This should work

$query->where('date_start', '>', $dateStart)->where('date_end', '<=', $dateEnd)->get();

Upvotes: 1

Related Questions