Laravel中如何统计用户当月新增的帖子数量?
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();
whereMonthfilters records to only those created in the specified monthwhereYearensures we only count posts from the current year (no old posts sneaking in)count()replacesget()to return just the numeric total instead of a post collection
Method 2: Use Carbon for Exact Date Range (Recommended)
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

