Reputation: 3274
I've been struggling with date range between (single column ) created_at column, so far i tried this
$startDate = date('Y-m-d', strtotime($request->start_date));
$endDate = date('Y-m-d', strtotime($request->end_date));
....->whereBetween('created_at', [$startDate,$endDate])
created_at format is by default ( Y-m-d H:i:s ), in post data i'm getting this format ( Y-m-d )
I know it's wrong query,but how should i think ?
Do i've to use ->whereRaw()
? or something with ->whereDate
?
Please help
Upvotes: 1
Views: 2650
Reputation: 12277
you have a dedicated function in Laravel for this purpose only whereDate()
. You can use it like so:
$startDate = date('Y-m-d', strtotime($request->start_date));
$endDate = date('Y-m-d', strtotime($request->end_date));
....->whereDate('created_at', '>', $startDate)->whereDate('created_at', '<', $endDate)
Furthermore, you could use <=
and >=
for the inclusion of limits.
And dont worry about "created_at format is by default ( Y-m-d H:i:s ), in post data i'm getting this format ( Y-m-d )", because the function only compares the Date part not the time stamp part so you are good to go.
Reference here
Upvotes: 4
Reputation: 3274
WAHH....very silly of me without trying everything i was asking question, it was as simple as it sound :-
->where('created_at', '>=', $fromDate->toDateString())->where('created_at', '<=', $toDate->toDateString())
Thank you so much and very sorry for silliness of mine.
Upvotes: 0
Reputation: 1556
to check between two dates you should use this:
$fromDate =Carbon::parse($request->start_date);
$toDate = Carbon::parse($request->end_date);
Model::whereBetween('created_at', [$fromDate->toDateString(), $toDate->toDateString()])->get();
Upvotes: 0