charles
charles

Reputation: 384

How to whereDate, whereMonth a variable?

I want to display the total payments overall, and total payments for this month using only one variable.

Controller

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

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

View

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

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

Actually the total payments overall displayed. But the "for this month" it is not working and returns me an error below:

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


Someone could tell me where I went wrong? and proper way to achieve this?

Upvotes: 0

Views: 943

Answers (2)

IronMan
IronMan

Reputation: 1960

so whereMonth is unfortunately only available with the query builder. You could filter the items after they've been retrieved:

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

Upvotes: 2

matticustard
matticustard

Reputation: 5149

Isn't querying by month alone going to create a problem later when you have more than one year of data? I would just use the start of the current month.

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

Upvotes: 2

Related Questions