- Published on
ELOQUENT WHERE DATE METHODS SAVE YOUR TIME
- Authors
-
-
Tags
-
Share
-
Laravel eloquent has some magic where methods for date filter, many of us probably doesn't know which can save our time and easy to remember.
1.) Let's say, we want to retrieve all user of a specific date using eloquent where method. We can achieve this using the following code.
App\Models\User::where('DATE(created_at)', '=', '2021-01-18')->get(); Eloquent has a shortcut for this. App\Models\User::whereDate('created_at', '2021-01-18')->get();
2.) If we want to retrieve all uses of a month we can use
App\Models\User::where(\DB::raw('MONTH(created_at)'), '01')->get(); Alternatively we can use the following eloquent whereMonth method. App\Models\User::whereMonth('created_at', '01')->get();
3.) If we want to retrieve all users of a specific day we can use:
App\Models\User::where(\DB::raw('DAY(created_at)'), '18')->get(); Alternative way to achieve this : App\Models\User::whereDay('created_at', '18')->get();
4.) We can retrieve all uses of a specific year using the following code:
App\Models\User::where(\DB::raw('YEAR(created_at)'), '2021')->get(); Alternative way: App\Models\User::whereYear('created_at', '2021')->get();
5.) We can retrieve all users of a specific time:
5.) We can retrieve all users of a specific time: App\Models\User::where(\DB::raw('TIME(created_at)'), '12:00:00')->get(); Using eloquent where magic method: App\Models\User::whereTime('created_at', '12:00:00')->get();