How to select all rows for a certain month (or day, year or time), using Eloquent
October 26, 2018
Eloquent makes many things easy, and working with dates is one of them!
There are bunch of built in functions for building a query that work with dates and times:
- whereDate
- whereMonth
- whereDay
- whereYear
- whereTime
You can use them like this:
You can use the whereDate()
method to compare a column's value against a date:
$users = DB::table('users')
->whereDate('created_at', '2020-11-31')
->get();
The whereMonth()
method can be used for comparing a column's value against a specific month of a year:
$users = DB::table('users')
->whereMonth('created_at', '10')
->get();
The whereDay()
method may be used to compare a column's value against a specific day of a month:
$users = DB::table('users')
->whereDay('created_at', '20')
->get();
The whereYear()
method may be used to compare a column's value against a specific year:
$users = DB::table('users')
->whereYear('created_at', '2020')
->get();
The whereTime()
method may be used to compare a column's value against a specific time:
$users = DB::table('users')
->whereTime('created_at', '=', '11:20:45')
->get();