Laravel foreach所有产品的总价格

时间:2020-05-07 16:47:31

标签: php laravel foreach

在Laravel中,如果我想获得购物车中所有产品的总价,我应该在代码中添加什么?这是cart.blade.php文件:

@extends('layouts.app')
@section('content')

<main class="container">

  <section class="row justify-content-center">

   <h1 class="text-center mb-5">Products on your cart:</h1>

  </section>

  <section class="row justify-content-center">

  @foreach(Auth::user()->computers()->get() as $computer)

  <div class="col-12 col-md-4">

   <h2 class="text-center">{{$computer->name}}</h2>
   <img class="card-img-top" src="{{Storage::url($computer->img)}}" alt="">
   <form action="{{route('computers.removepc',['id'=>$computer->id])}}" method="POST">
   @csrf 
   <center><button class="btn btn-danger mb-5" type="submit">Remove</button></center>
   <p class="text-center">Price: {{$computer->price}}</p> //This is the single price of each product

   </div>

 @endforeach


 </section>

 <section class="row justify-content-center">
  <h1>Here I want the total price</h1> //Here is , for example, where i want the total price of all computers in the cart
 </section>

 </main>
 @endsection

感谢帮助!

1 个答案:

答案 0 :(得分:1)

尝试在@foreach上方添加$ total变量,像这样:

<?php $total = 0; ?>

然后在@foreach内添加以下内容:

 <?php $total+= $computer->price  ?>

然后转到要输出总计的位置并写:

   {{$total}}