EN VI

Php - Get grand total from foreach looping laravel?

2024-03-10 13:00:04
How to Php - Get grand total from foreach looping laravel

The $grand_total is always returning the last of $row value. Example : if the last row have subtotal 100000 , then grand total returning 100000 too.

       @foreach ($cart as $row)
        @php
            $sub_total= $row->price * $row->qty;
            $grand_total = 0;
        @endphp
                <ul style="list-style: none;">
                    <li>Product Name : {{$row->product_name}}</li>
                    <li><b>{{$row->price}}</b></li>
                    <li>Qty : {{$row->qty}}</li><br>
                    <li><b>Total : {{$sub_total}}</b></li>
                </ul>
        @php
            $grand_total += $sub_total;
        @endphp
        @endforeach
    
        <a href="/payment">
        <button style="width: 180px; height: 60px; font-size: 15px;">Checkout : 
        Rp. {{$grand_total}} </button>
        </a>

Or maybe I should have some change on my controller ?

Solution:

You're resetting $grand_total to 0 in each loop iteration. You should initialize $grand_total before the loop starts and then add $sub_total to each iteration.

@php
    $grand_total = 0;
@endphp

@foreach ($cart as $row)
    @php
        $sub_total= $row->price * $row->qty;
        $grand_total += $sub_total;
    @endphp
    <ul style="list-style: none;">
        <li>Product Name : {{$row->product_name}}</li>
        <li><b>{{$row->price}}</b></li>
        <li>Qty : {{$row->qty}}</li><br>
        <li><b>Total : {{$sub_total}}</b></li>
    </ul>
@endforeach

<a href="/payment">
    <button style="width: 180px; height: 60px; font-size: 15px;">Checkout : 
    Rp. {{$grand_total}} </button>
</a>
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login