Reint
Reint

Reputation: 165

Laravel Query Builder - Where date is now using carbon

How to get only date on database column, I have difficulties using Carbon on controller:

$data['nowUser'] = User::where('date', Carbon::today()->toDateString())->get();

Date column looks like this in the database:

enter image description here

Upvotes: 10

Views: 22898

Answers (1)

Bogdan
Bogdan

Reputation: 44526

That is a DATETIME column, so there's no need for additional formatting the Carbon instance. However you need to use whereDate if you want the fetch all users for which the date column contains today's date:

$data['nowUser'] = User::whereDate('date', '=', Carbon::today())->get();

Because when you pass Carbon::today() to the Query Builder method, the __toString method will be automatically called and return a DATETIME string with the format from Carbon::DEFAULT_TO_STRING_FORMAT, which is exactly that MySQL format Y-m-d H:i:s.

Upvotes: 22

Related Questions