MrBelongsTo
MrBelongsTo

Reputation: 43

Count all elements from some day

I have this code:

$currentDate =  Carbon::now()->subDays(1);
$count = MyPosts::where('created_at', $currentDate)->count();

Problem is that it doesn't find any elements because time can be different. I want to count all elements from particular day.

Upvotes: 0

Views: 28

Answers (1)

Joel Hinz
Joel Hinz

Reputation: 25414

You can compare it to the specific day, and ask Carbon to give you the date rather than the datetime. The syntax is pretty simple:

$date = now()->subDay()->toDateString();
$count = MyPosts::whereDate('created_at', $date)->count();

On a related note, it's better to name models in the singular (MyPost) because each instance of it is a single object. The table is plural my_posts because it contains many of them.

Upvotes: 1

Related Questions