Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

StarShines's avatar

Sum amount in foreach loop

Hello,

I am able to get students fees in table row like this:

<td>
                                @foreach($invoice->studentName as $key => $entry)
                                    {{ $entry->student_fee }}
                                @endforeach
                            </td>

It shows amounts individually. How can I sum the fees.

Thank you

0 likes
6 replies
LaryAI's avatar
Level 58

You can create a variable to store the sum of the fees and add each fee to it in the foreach loop. Then, you can display the total sum outside of the loop. Here's an example:

<td>
    @php
        $totalFees = 0;
    @endphp
    @foreach($invoice->studentName as $key => $entry)
        {{ $entry->student_fee }}
        @php
            $totalFees += $entry->student_fee;
        @endphp
    @endforeach
    Total: {{ $totalFees }}
</td>

In this example, we create a variable $totalFees and initialize it to 0 before the loop. Inside the loop, we add each fee to the total using the += operator. Finally, we display the total outside of the loop.

tisuchi's avatar
tisuchi
Best Answer
Level 70

@shunmas I think you can use this also.

@php
    $totalFee = $invoices->studentName->sum('student_fee');
@endphp

Total Fee: {{ $totalFee }}
1 like
StarShines's avatar

@laryai @tisuchi Thanks for your replies.

Yes, this works in blade:

{{ $invoice->studentName->sum('student_fee') }}
1 like
tisuchi's avatar

@shunmas If you hover on any answer, you will see the Set Best Answer.

Simply select the answer that you believe resolves your issue and mark it as the "Best Answer."

For example-

1 like

Please or to participate in this conversation.