如何给whereDate,whereMonth一个变量?

How to whereDate, whereMonth a variable?

我想仅使用一个变量显示总体付款本月的总付款。

控制器

$payments = Payment::where('user_id', auth()->user()->id)->get();

return view('subscribers.payments', compact(['payments']));

查看

<label>Total payments</label>
<p>{{ $payments->sum('amount') }}</p>

<label>For this month</label>
<p>{{ $payments->whereMonth('created_at', now()->month)->sum('amount') }}</p>

实际上 显示的总付款。但是 "for this month" 它不起作用并且 returns 我在下面出现错误:

Method Illuminate\Database\Eloquent\Collection::whereMonth does not exist.


有人可以告诉我哪里出错了吗?以及实现此目标的正确方法?

so whereMonth 不幸的是只适用于查询生成器。您可以 filter 检索项目后:

$payments->filter(function ($payment) {
    return $payment->created_at->month == now()->month;
})->sum('amount') 

当您拥有超过一年的数据时,单独按月查询不会产生问题吗?我只会使用当月的开始。

<p>{{ $payments->where('created_at', '>=', now()->startOfMonth())->sum('amount') }}</p>