我正尝试在用户注销时获取特定用户的购物车商品,因此应该从购物车中删除购物车商品。如何获取,请帮助我,谢谢吗?
控制器
public function addCart(Request $request)
{
$product = Product::findOrFail($request->id);
$cartItem = Cart::add([
'id' => $product->id,
'name' => $product->product_name,
'brand'=>$product->product_brand,
'image'=>$product->product_image,
'qty' => $request->qty,
'price' => $product->product_price,
]);
Cart::associate($cartItem->rowId, 'App\Product');
return redirect()->route('cart.index');
}
答案 0 :(得分:1)
您的模型缺少与用户的关系-当前,仅当您网站上只有一个用户时,您解决此问题的方式才有效。
这意味着:
使用user_id扩展Cart
的迁移,在模型中定义关系。
之后,您可以收听Logout
事件:https://laravel.com/api/5.6/Illuminate/Auth/Events/Logout.html处理“删除”的逻辑
您只需执行以下操作:Cart :: whereUserId($ event-> userId)-> get(),您就会获得所有购物车商品。
有关事件的更多信息:https://laravel.com/docs/6.x/events