Laravel AVG() Limit to 3 Most Recent Records

Viewed 30

I am trying to calculate the average usage of the 3 most recent transactions in my DB for a billing dispute system but got an error instead:

Call to a member function get() on string

Here's how I called it on my controller:

$avg = Billing::where('accountNo', $request->referenceCode)
    ->orderBy('dateCreated')
    ->limit(3)
    ->avg('usage')
    ->get()
;

And on my blade it's displayed like this:

<tbody class="text-center">
    @foreach ($billing as $b)
    <tr>
        <td class="whitespace-nowrap">{{ date('M Y', strtotime($b->dateCreated)) }}</td>
        <td class="whitespace-nowrap">{{ $b->usage }}m³</td>
        <td class="whitespace-nowrap">₱{{ $b->amount }}</td>
    </tr>

    @endforeach
    <tr style="font-weight: bold; color: #1e293b; background-color: #f1f5f9;">
        <td class="whitespace-nowrap">Average</td>
        <td class="whitespace-nowrap">{{ number_format($avg, 2) }} m³</td>
    </tr>
</tbody>

Did I miss something?

1 Answers

The avg method returns a value. You don't need to call get after avg, Laravel does that for you. Just remove the get method after avg.

Related