对两个变量求和

时间:2019-01-29 12:16:33

标签: laravel eloquent laravel-5.7

他试图获取多个商品的总价作为总价,但它显示了单个单一产品的总价,图片为:https://ibb.co/YkZgfXV

这是cart.blade.php的代码:

   <table>
   <tr class="table-row">
                        <?php $total_amount = 0; ?>
                        @foreach($userCart as $cart)
                        <td class="column-1">
                            <div class="cart-img-product b-rad-4 o-f-hidden">
                                <img src="{{ asset('images/backend_images/products/small/'.$cart->image) }}" alt="IMG-PRODUCT">
                            </div>
                        </td>

                        <td class="column-2">{{ $cart->product_name }}</td>
                        <td class="column-3">PKR: {{ $cart->price }}</td>
                        <td class="column-4">
                            <div class="flex-w bo5 of-hidden w-size17">
                                <a class="cart_quantity_up color1 flex-c-m size7 bg8 eff2" href="{{ url('/cart/update-quantity/'.$cart->id.'/1') }}">+</a>
                                <input class="size8 m-text18 t-center num-product" type="number" name="quantity" value="{{ $cart->quantity }}">
                                @if($cart->quantity>1)
                                <a class="cart_quantity_down color1 flex-c-m size7 bg8 eff2" href="{{ url('/cart/update-quantity/'.$cart->id.'/-1') }}">-</a>
                                @endif
                            </div>
                        </td>
                        <td class="column-5">PKR: {{ $cart->price }}</td>
                        <td class="column-6"><a href="{{ url('/cart/delete-product/'.$cart->id)}}">X</a></td>
                    </tr>
                        @endforeach
                </table>

        <!-- Total -->
            <div class="flex-w flex-sb-m p-t-26 p-b-30">
                @foreach($userCart as $cart)
                <span class="m-text22 w-size19 w-full-sm">
                    Total:
                </span>

                <span class="m-text21 w-size20 w-full-sm">
                    PKR: {{ $cart->price*$cart->quantity }}
                </span>
                @endforeach
            </div>

2 个答案:

答案 0 :(得分:0)

在显示购物车之前,您需要计算其总数。像这样:

<div class="flex-w flex-sb-m p-t-26 p-b-30">
    @php 
        $total = 0; 
        foreach($userCart as $cart) {
            $total += ($cart->price * $cart->quantity); 
        }
    @endphp
    <span class="m-text22 w-size19 w-full-sm">
        Total:
    </span>
    <span class="m-text21 w-size20 w-full-sm">
        PKR: {{ $total }}
    </span>
</div>

您可以按原样保留上面的html。而且,视图中不应包含这种逻辑。例如,它应该在控制器中。

答案 1 :(得分:0)

我无法评论其他答案,但这是Mozammil的意思:

在foreach循环中,每次循环时都显示“总计”。

@foreach($userCart as $cart)
    <span class="m-text22 w-size19 w-full-sm">
    Total:
    </span>

    <span class="m-text21 w-size20 w-full-sm">
    PKR: {{ $cart->price*$cart->quantity }}
    </span>
@endforeach

仅在循环中执行计算,然后在循环外部显示总计。检查Mozammil的答案以获取正确的代码。