$users = User::whereMonth('created_at', date('m'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->month;
//select * from `users` where month(`created_at`) = "04"
$users = User::whereDay('created_at', date('d'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->day;
//select * from `users` where day(`created_at`) = "03"
$users = User::whereYear('created_at', date('Y'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->year;
//select * from `users` where year(`created_at`) = "2017"
For readability purposes i use query scope, makes my code more declarative.
scope query
namespace App\Models;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
// ...
/**
* Scope a query to only include today's entries.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCreatedToday($query)
{
return $query->where('created_at', '>=', Carbon::today());
}
// ...
}
example of usage
MyModel::createdToday()->get()
SQL generated
Sql : select * from "my_models" where "created_at" >= ?
Bindings : ["2019-10-22T00:00:00.000000Z"]
Carbon::today() will return something like this: 2021-08-06T00:00:00.000000Z, so using Model::where('created_at', Carbon::today()) will only return records created at exactly 12:00 am current date.
Use Model::where('created_at', '>=', Carbon::today()) instead