Reputation: 2439
I'm doing a whereBetween
dates query on Eloquent. However, I have an issue with the date time.
If I select date_from to 2018-11-01
and date_to to 2018-11-29
and if I have a data that was created on 2018-11-29 12:28:45
the data created on this datetime will not be included because of the time.
Is there a way to cast the created_at
to date
?
here's my code:
Payable::with('details', 'transaction_type')
->whereBetween('created_at', [$request->date_from, $request->date_to])
->get();
Upvotes: 1
Views: 1534
Reputation: 1050
You can set time to your date variables.
$request->date_from = $request->date_from . ' 00:00:00';
$request->date_to = $request->date_to . ' 23:59:59';
Upvotes: 1
Reputation: 2016
If you don't mind adding an extra ->
to your querying, you can very easily do this:
Payable::with('details', 'transaction_type')
->whereDate('created_at', '>=', $request->date_from)
->whereDate('created_at', '<=', $request->date_to)
->get();
Upvotes: 0
Reputation: 2243
I feel a much cleaner way to handle dates in Laravel is using the Carbon package.
$date_from = Carbon::createFromFormat('Y-m-d', $request->date_from)->startOfDay();
$date_to = Carbon::createFromFormat('Y-m-d', $request->date_to)->endOfDay();
Just FYI, created_at
column when accessed via eloquent will return a carbon date object by default.
Hope this helps.
K
Upvotes: 0