Imagine you want to filter some data like for example sales by month, year, or by a custom range, Laravel offers a convenient way to do that.
Let's see how we can do it.
Filter by Year
Sale::whereYear('date_sale', date('Y'))->get();
Filter by Month
Sale::whereMonth('date_sale', date('m'))->get();
Filter by Day
Sale::whereDay('date_sale', date('d'))->get();
Filter by Date
Sale::whereDate('date_sale', '2021-10-10')->get();
Filter by Custom Range
Sale::whereBetween('date_sale', ['2021-05-30', '2021-10-30'])->get();
Note: As you can see whereDate
receive a date in format Y-m-d
if you are receiving parameters from a datepicker in a different format you can use Carbon
to change the format.
Thanks for reading.