购物车页面实现总价计算,有需要的可以参考下
product index.blade.php 新增代码
<table class="table table-striped">
<thread>
<tr>
<th>总价:¥{{ $total }}</th>
</tr>
</thread>
</table>
购物车控制器
// 查看购物车
public function index(Request $request)
{
// 预加载获取购物车中的商品信息,避免重复查询
$cartItems = $request->user()->cartItems()->with(['productSku.product'])->get();
// 获取总金额
$total = 0;
foreach($cartItems as $item){
if ($item->productSku->product->on_sale) {
$total += $item->productSku->price * $item->amount;
}
}
return view('cart.index', compact('cartItems', 'total'));
}
推荐文章: