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.
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.
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 year, month, and day.
User::whereYear('created_at', '2024')->first();User::whereMonth('created_at', '03')->first();User::whereDay('created_at', '1')->first();
I will show you a technique that is not recommended, and I haven't even found that in the documentation, but it's a nifty trick to know. I never used it, and I don't recommend it.
You can prefix where with the column name. For example, typically, when searching for email, you would do the following:
User::where('email', 'test@test.com')->first();
But you can do it like this:
User::whereEmail('test@test.com')->first();
Also, you can provide more columns with the word and
.
User::whereEmailAndCreatedAt('test@test.com', '2023-03-01')->first();
These are cool to know things, but I would never use them because it is impossible to search for fields. For example, if you were renamed some field and needed to search for a specific field in your code base, you would need help finding it.
And it's not more readable. It's short on the code by a few symbols, but it's not worth it.