I have a list of database records that represent some events. Each has a start_time
column that contains dates in this format: 2017-10-28 22:00:00
. I would like to be able to get all the records whose column start_time
is a Friday using Laravel. Something like this:
$fridayEvents = $q->whereDate('start_time', '=', isFriday());
But I am having a hard time creating isFriday()
with Carbon.
MySQL (and other SQLs) implement the WEEKDAY() function that extracts the weekday from a date:
WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).
mysql> SELECT WEEKDAY('2008-02-03 22:23:00'); -> 6 mysql> SELECT WEEKDAY('2007-11-06'); -> 1
So you can do a query like this:
$q->whereRaw('WEEKDAY(your_table_name.start_date) = 4')
This way is more efficient then filtering results directly on PHP using Carbon:
To get the top performance, you'll need to create a column to store the weekday, so your database will be able to use indexes to avoid full-table scan, giving you the best performance.