What if you have a timestamp or datetime column and want to query by date? How do you filter that? There are a few ways to use raw queries, but I will show you a few helpful methods in Laravel.
Example 1: DB::raw()
Because created_at
is a datetime column, the SQL date
function can be used.
User::where(\DB::raw('DATE('created_at)'), '2024-03-01')->first();
And, of course, it returns the user registered on that date.
Example 2: whereDate()
Instead of doing DB::raw()
and using SQL functions, you can use the whereDate()
Eloquent method.
User::whereDate('created_at', '2024-03-01')->first();
Also, instead of date
, you can check...