skip to Main Content

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 ?

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. because $grand_total is inside the for loop, take it out from the loop and you will be fine with the problem:

    @php
    $grand_total = 0;
    @endphp
    @foreach ($cart as $row)
        @php
            $sub_total= $row->price * $row->qty;
            
        @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>
    

    That should works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search