首页 > 解决方案 > Laravel Ajax 使用选择选项更新购物车中的项目

问题描述

我想用一个选择选项来更新我的购物车中的商品数量,所以当我的购物车中有两个或更多产品时,当我尝试更改其中一个数量项目的产品时,我的购物车中的每个产品都会更新为我发送的相同信息。

HTML 选择选项

<select class="select quantity" detail-id="{{ $detail->id }}" product-id="{{ $detail->product->id }}" product-type="{{ $detail->type }}">

@php
  if($detail->type == 'Unidad' || $detail->type == 'Unit' || $detail->type == 'Einheit'){
    $limit = $detail->product->unit_stock;
  } else if($detail->type == 'Caja' || $detail->type == 'Box'){
    $limit = floor($detail->product->unit_stock / $detail->product->pcs_box);
  }
@endphp

@for($i = 0; $i <= $limit; $i++)
  <option value="{{ $i }}" {{ $i == $detail->quantity ? 'selected' : '' }}> {{ $i }} </option>
@endfor

</select>

AJAX

$('.quantity').change(function () {

            var productId = $(this).attr('product-id');
            var cartDetail = $(this).attr('detail-id');
            var productType = $(this).attr('product-type');
            var productQty = $(this).find(':selected').index();

            // console.log(productId);
            // console.log(cartDetail);
            // console.log(productType);
            // console.log(productQty);

            loadItemCart(productId, cartDetail, productType, productQty);

        });

        function loadItemCart(productId, cartDetail, productType, productQty){
            $.ajax({
                method: 'POST',
                url: '/cart-qty',
                data: {
                    detail: cartDetail,
                    type: productType,
                    product: productId,
                    quantity: productQty,
                },
                success: function (res) {

                    if(res.status == 'success'){
                        toastr.success(res.message);
                        window.setTimeout(function(){location.reload()},1500)
                    }

                    if(res.status == 'error'){
                        toastr.error(res.message);
                        window.setTimeout(function(){location.reload()},1500)
                    }

                }
            });
        }

控制器

public function cartQty(Request $request)
{

    $cartDetail = CartDetail::where([
        ['cart_id', auth()->user()->cart->id],
        ['id', $request->detail],
        ['product_id', $request->product]
    ])->firstOrFail();

    ...
    
}

标签: ajaxlaravel

解决方案


推荐阅读