Laravel:点击按钮传递指定商铺ID至控制器实现购物车删除
解决Laravel中点击按钮删除指定商铺购物车数据的问题
原代码的核心问题
- 循环生成的所有表单共用同一个
id="x-cart",HTML要求id必须唯一,会引发DOM操作冲突 - 删除按钮是
type="button",不会自动触发表单提交,点击后无任何提交行为 - 用数组类型的
shop-to-remove[]完全没必要,单个删除操作仅需传递当前商铺ID,数组反而增加处理复杂度
修改后的Blade模板代码
@foreach ($getShopName as $shop) {{-- 每个商铺对应独立表单,用shop ID做唯一标识 --}} <form id="delete-cart-{{ $shop->id }}" action="{{ route('cartconfigurations') }}" method="post"> @csrf {{-- 直接传递单个商铺ID,无需数组 --}} <input type="hidden" name="shop_id" value="{{ $shop->id }}"> <input type="hidden" name="action" value="deleteshop"> {{-- 给复选框加唯一id,和label的for属性对应 --}} <input class="shop-radio" type="checkbox" name="shop-radio[]" value="{{ $shop->id }}" data-seller-id="{{ $shop->id }}" id="formCheck-{{ $shop->id }}"> <label class="form-check-label" for="formCheck-{{ $shop->id }}">{{ $shop->shop_name }}</label> {{-- 按钮改为submit类型,点击直接提交当前表单 --}} <button class="btn d-xxl-flex close delete-shop-button" type="submit"> X </button> </form> @endforeach
注:原代码中
label的for属性是固定值,会导致所有label指向同一个复选框,这里改成和当前商铺复选框的id匹配,保证点击label能正确选中对应复选框。
控制器处理逻辑
在cartconfigurations路由对应的控制器方法中,直接接收参数并执行删除:
public function cartConfigurations(Request $request) { if ($request->input('action') === 'deleteshop') { // 验证参数有效性 $validated = $request->validate([ 'shop_id' => 'required|integer|exists:shops,id' // 假设商铺表名为shops ]); // 删除Carts表中该商铺的关联数据 \App\Models\Cart::where('shop_id', $validated['shop_id'])->delete(); // 返回提示并跳转回原页面 return redirect()->back()->with('success', '该商铺的购物车数据已删除'); } // 其他业务逻辑... }
可选:AJAX无刷新删除方案
如果不想页面刷新,可保留按钮type="button",用JS监听点击事件提交请求:
@foreach ($getShopName as $shop) <div class="shop-item"> <input class="shop-radio" type="checkbox" name="shop-radio[]" value="{{ $shop->id }}" data-seller-id="{{ $shop->id }}" id="formCheck-{{ $shop->id }}"> <label class="form-check-label" for="formCheck-{{ $shop->id }}">{{ $shop->shop_name }}</label> <button class="btn d-xxl-flex close delete-shop-button" type="button" data-shop-id="{{ $shop->id }}"> X </button> </div> @endforeach {{-- 隐藏表单用于AJAX提交 --}} <form id="delete-cart-form" action="{{ route('cartconfigurations') }}" method="post" style="display:none;"> @csrf <input type="hidden" name="shop_id" id="delete-shop-id"> <input type="hidden" name="action" value="deleteshop"> </form> <script> document.querySelectorAll('.delete-shop-button').forEach(button => { button.addEventListener('click', function() { const shopId = this.dataset.shopId; document.getElementById('delete-shop-id').value = shopId; // 提交表单(有刷新) document.getElementById('delete-cart-form').submit(); // 可选:用fetch实现无刷新删除 /* fetch("{{ route('cartconfigurations') }}", { method: 'POST', headers: { 'X-CSRF-TOKEN': "{{ csrf_token() }}", 'Content-Type': 'application/x-www-form-urlencoded' }, body: `shop_id=${shopId}&action=deleteshop` }).then(res => res.json()) .then(data => { if (data.success) { this.closest('.shop-item').remove(); } }); */ }); }); </script>
内容的提问来源于stack exchange,提问作者Sequoia
相关产品推荐
相关产品推荐

