Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

LovelyBoy's avatar

Created at date only

Guys i want to show sum of calerios that user taken on current day how can i use today date in my query like this

 $takendiet = DietTaken::where('user_id',$auth_id)->where('created_at','2015-08-15')->sum('eaten_calories');

how can i show created_at date only

0 likes
12 replies
bobbybouwmann's avatar

You can do something like this

->where(DB::raw('CURDATE(created_at)'), '=', Carbon::now()->format('Y-m-d'))->sum('eaten_calories');
1 like
jekinney's avatar

Or

->where('created_at', Carbon::today())->sum('eaten_calories');
1 like
LovelyBoy's avatar

@bobbybouwmann query not working syntax error

select sum(`eaten_calories`) as aggregate from `diet_takens` where `user_id` = 15 and CURDATE(created_at) = 2015-08-15
thomaskim's avatar
Level 41

@LovelyBoy I'd do what jekinney did but modify it a bit.

 $takendiet = DietTaken::where('user_id',$auth_id)
    ->where('created_at', '>=', Carbon::today())
    ->where('created_at', '<', Carbon::tomorrow())
    ->sum('eaten_calories');
1 like
jekinney's avatar

@thomaskin isn't your query end up the same as what I posted?

Just got me thinking. The today method returns todays date with out time. So it looks for all created at with todays date only.

martinbean's avatar

@LovelyBoy There’s a query builder method exactly for this:

DietTaken::where('user_id', '=', $auth_id)
         ->whereDate('created_at', '=', Carbon::today())
         ->sum('eaten_calories');
1 like
thomaskim's avatar

@martinbean Great stuff. I wasn't aware of that.

@jekinney Wouldn't your original query only find ones that were created today at the time 00:00:00?

jekinney's avatar

Curiosity got me....

$takendiet = DietTaken::where('user_id',$auth_id)
    ->where('created_at', '>=', Carbon::today())
    ->where('created_at', '<', Carbon::tomorrow())
    ->sum('eaten_calories');

returns the same as

$takendiet = DietTaken::where('user_id',$auth_id)
    ->where('created_at', '=', Carbon::today())
    ->sum('eaten_calories');

The reason I was thinking was the first query compares created_at by greater then and equal to today's date on the first where then compares created_at is less then tomorrows date, which is the same as equals today's date only as per the second query. It had me wondering is all what the difference was. Other then being less efficient, it is ultimately the same query as they return the exact same results.

@thomaskin

Carbon::today()

only returns the date no time. So the date comparison will compare date not time. I know as I have used that query a lot for graph data for backend to show sign ups, subscriptions etc

Please or to participate in this conversation.