如何从Laravel集合中获取store_id并传递至表单action?
解决方案
步骤1:修改控制器获取store_id
因为所有购物车项的store_id一致,直接从Cart集合的第一个模型中提取即可,同时建议用预加载优化查询性能:
public function index(Request $request) { $itemuser = $request->user(); // 预加载Product和Store,避免N+1查询 $cart = Cart::with('Product.Store')->where('user_id', $itemuser->id)->get(); $cartdetail = CartDetail::where('user_id', $itemuser->id)->get(); $carts = $cart->groupBy(fn ($i) => $i->Product->Store->name); // 获取唯一的store_id,用可选链式调用避免空集合报错 $storeId = $cart->first()?->Product->Store->id; return view('customer.cart', [ 'title' => 'Cart', 'carts' => $carts, 'cartdetail' => $cartdetail, 'storeId' => $storeId // 传递到视图 ]); }
步骤2:修改视图使用store_id
直接在表单action中使用传递过来的$storeId:
<form action="/editshipping/{{ $storeId }}" method="POST"> @csrf ... </form>
报错原因说明
你之前用$carts->store_id报错,是因为$carts是分组后的集合,结构为[店铺名称 => 对应Cart模型集合, ...],它本身并没有store_id属性。store_id属于单个Cart模型关联的Store对象,必须从具体的Cart实例中获取。
内容的提问来源于stack exchange,提问作者baihaqi
相关产品推荐
相关产品推荐

