Let's say you want to filter out entries created today. You have a timestamp field created_at, right? How do you filter the DATE only from that timestamp? Apparently, Taylor thought about it.
I've seen people doing it with raw queries, like this:
$q->where(DB::raw("DATE(created_at) = '".date('Y-m-d')."'"));
Or without raw queries by datetime, like this:
$q->where('created_at', '>=', date('Y-m-d').' 00:00:00'));
Luckily, Laravel Query Builder offers a more Eloquent solution:
$q->whereDate('created_at', '=', date('Y-m-d'));
Or, of course, instead of PHP date() you can use Carbon:
$q->whereDate('created_at', '=', Carbon::today()->toDateString());
Wait, there's more
It's not only whereDate. There are four more useful functions to filter out dates:
$q->whereDay('created_at', '=', date('d')); $q->whereMonth('created_at', '=', date('m')); $q->whereYear('created_at', '=', date('Y')); $q->whereTime('created_at', '=', date('H:m:s'));
Isn't it nice and easy?
The only thing is if you're dealing with timezones, you should totally use Carbon and make some more complex queries, but that's a topic for a whole another article.
Video version
You can watch how it works - in my video WhereX Magic Methods for Fields and Dates.
It's a lesson from my 2-hour online-course Eloquent: Expert Level.
No comments or questions yet...