如何通过product_id从购物车会话中删除产品? 我已经使用Ajax将产品ID发送到控制器。这些是我的代码,这就是我的购物车会话的结构
会话的json结构:
[{"product_id":"2","quantity":5,"userId":"1","product_name":"\u062f\u0645\u067e\u0627\u06cc\u06cc \u0627\u0628\u0631\u06cc ","product_root":"files\\courses\\course2","product_description":"\u062f\u0645\u067e\u0627\u06cc\u06cc \u0627\u0628\u0631\u06cc ","product_price":5000},{"product_id":"1","quantity":1,"userId":"1","product_name":"\u062a\u0645\u0628\u0648\u0646 \u06cc\u0632\u062f\u06cc\u0645 \u0645\u0627\u0644 \u062a\u0648 ","product_root":"files\\courses\\course1","product_description":"asdasdasdasdsadsadsadas","product_price":1000}]
控制器功能:
public function deleteCardItem(Request $request)
{
$product_id = $request-> id;
$cards = session()->get('cards');
$ids = array_column($cards, 'product_id');
$index = array_search($product_id, $ids);
unset($cards[$index]);
}
ajax:
$.ajax({
type: 'post',
url: '{{route('deleteCard')}}',
data: {
'id':Product_id,
'userId':'{{auth()->user()->id}}',
"_token": '{{ csrf_token() }}',
},
cache: false,
success: function(res){
}
});
答案 0 :(得分:1)
您可以使用array_filter查找并删除已删除的项目:
public function deleteCardItem(Request $request)
{
$product_id = $request-> id;
$cards = session()->get('cards');
$newCards = array_filter($cards, function($product){
return $product['product_id'] != $product_id;
});
session($newCards);
}