You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何统计用户当月新增的帖子数量?

Fixing Laravel Monthly Post Count

Hey there! Let's get your monthly post count working correctly. Your current code has two key issues:

  • It only checks the month, not the year (so it would include posts from the same month in previous years)
  • You're using get() which returns a full collection of posts instead of just the numeric count you need

Here are a couple of clean, reliable ways to get the exact number you want:

Method 1: Use Laravel's Built-in Date Query Methods

Laravel's query builder has handy whereMonth and whereYear methods that make this straightforward:

$currentMonth = date('m');
$currentYear = date('Y');

$monthlyPostCount = DB::table("posts")
    ->whereMonth('created_at', $currentMonth)
    ->whereYear('created_at', $currentYear)
    ->count();
  • whereMonth filters records to only those created in the specified month
  • whereYear ensures we only count posts from the current year (no old posts sneaking in)
  • count() replaces get() to return just the numeric total instead of a post collection

For even more precision, use Laravel's included Carbon library to target the full range of the current month:

use Carbon\Carbon;

$monthlyPostCount = DB::table("posts")
    ->whereBetween('created_at', [
        Carbon::now()->startOfMonth(),
        Carbon::now()->endOfMonth()
    ])
    ->count();

This approach automatically handles the start and end times of the current month (e.g., January 1st 00:00:00 to January 31st 23:59:59), so you don't have to manually track month/year values. It's cleaner and less error-prone!

Either of these methods will give you the numeric count of posts added this month, exactly what you're looking for.

内容的提问来源于stack exchange,提问作者Karar Jabr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:28:09