In this example, we will see Laravel whereDate(), whereMonth(), whereDay() and whereYear() Example.
Laravel whereDate, whereMonth, whereDay and whereYear Example
Certainly! In Laravel, the whereDate()
, whereMonth()
, whereDay()
, and whereYear()
methods are used to perform date-based queries on Eloquent models.
Suppose you have a model named Event
with a start_date
column in your database table. You can use these methods to filter records based on the date components.
Filtering by Specific Date
use App\Models\Event;
$specificDate = '2024-03-03';
$eventsOnSpecificDate = Event::whereDate('start_date', $specificDate)->get();
Filtering by Month
use App\Models\Event;
$month = 3; // March
$eventsInMarch = Event::whereMonth('start_date', $month)->get();
Filtering by Day
use App\Models\Event;
$day = 15;
$eventsOn15thDay = Event::whereDay('start_date', $day)->get();
Filtering by Year
use App\Models\Event;
$year = 2024;
$eventsIn2024 = Event::whereYear('start_date', $year)->get();
Combining Multiple Date Filters
use App\Models\Event;
$combinedQuery = Event::whereYear('start_date', $year)
->whereMonth('start_date', $month)
->whereDay('start_date', $day)
->get();
Dynamic Date Comparison using Carbon
use App\Models\Event;
use Carbon\Carbon;
$startDate = Carbon::now()->subDays(7); // Events in the last 7 days
$recentEvents = Event::whereDate('start_date', '>=', $startDate)->get();
Let's see all the code in one place
use App\Models\Event;
use Carbon\Carbon;
// Example 1: Filtering by specific date
$specificDate = '2024-03-03';
$eventsOnSpecificDate = Event::whereDate('start_date', $specificDate)->get();
// Example 2: Filtering by month
$month = 3; // March
$eventsInMarch = Event::whereMonth('start_date', $month)->get();
// Example 3: Filtering by day
$day = 15;
$eventsOn15thDay = Event::whereDay('start_date', $day)->get();
// Example 4: Filtering by year
$year = 2024;
$eventsIn2024 = Event::whereYear('start_date', $year)->get();
// You can also combine these methods for more complex queries
$combinedQuery = Event::whereYear('start_date', $year)
->whereMonth('start_date', $month)
->whereDay('start_date', $day)
->get();
// Using Carbon instance for dynamic date comparison
$startDate = Carbon::now()->subDays(7); // Events in the last 7 days
$recentEvents = Event::whereDate('start_date', '>=', $startDate)->get();
Remember to replace start_date
with the actual column name in your database. Make sure to change the variables according to your specific needs.
This is the simple way which allowing you to work with date related data in Laravel to filter Eloquent models which depend on different date components.