推送到数组会话 - Laravel 8.x
Posted
技术标签:
【中文标题】推送到数组会话 - Laravel 8.x【英文标题】:Pushing to array session - Laravel 8.x 【发布时间】:2021-08-06 19:48:28 【问题描述】:我想在会话数组中存储一个购物车。我正在尝试这样做:
class TestController extends Controller
function add($id, Request $request)
if ($request->session()->missing('shopping_cart'))
$request->session()->put('shopping_cart', []);
$item = array(
'id' => $id,
'quntity'=> 1
);
$request->session()->push('shopping_cart', $item);
输出:
[
0 => [
"id" => "12"
"quantity" => 1
]
]
但是当我再次调用函数 add() 时,它会像这样替换数组:
[
0 => [
"id" => "20"
"quantity" => 1
]
]
期望的输出:
[
0 => [
"id" => "12"
"quantity" => 1
]
1 => [
"id" => "20"
"quantity" => 1
]
2 => [
"id" => "27"
"quantity" => 1
]
]
【问题讨论】:
【参考方案1】:这可能是因为shopping_cart
是一个已经定义好的键。所以它会用那个键覆盖数据。您可以做的最好的事情是使用该shopping_cart
对象中的ID 创建一个唯一项。类似的东西;
function add($id, Request $request)
$shoppingCartKey = 'shopping_cart.'+ $id;
$shoppingCartData = array(
'quantity'=> 1
);
if ($request->session()->missing($shoppingCartKey))
$request->session()->put($shoppingCartKey, []);
$request->session()->push($shoppingCartKey, $shoppingCartData);
现在您还可以根据shopping_cart
ID/key 从会话中获取/拉取数据
【讨论】:
【参考方案2】:只要您将购物车 ID 带到您希望与购物车一起使用的每个功能,这就会对您进行排序。以下是将产品添加到购物车会话
public function addItem($id)
$post = Post::find($id);
if(!$post)
abort(404);
$cart = session()->get('cart');
// if cart is empty then this the first product
if(!$cart)
$cart = [
$id => [
"name" => $post->product_name,
"quantity" => 1,
"price" => $post->price,
]
];
session()->put('cart', $cart);
return redirect()->back()->with('toast_success', 'Product added to cart successfully!');
// if cart not empty then check if this product exist then increment quantity
if(isset($cart[$id]))
$cart[$id]['quantity']++;
session()->put('cart', $cart);
return redirect()->back()->with('toast_success', 'Product added to cart successfully!');
// if item not exist in cart then add to cart with quantity = 1
$cart[$id] = [
"name" => $post->product_name,
"quantity" => 1,
"price" => $post->price,
];
session()->put('cart', $cart);
return redirect()->back()->with('toast_success', 'Product added !!');
【讨论】:
以上是关于推送到数组会话 - Laravel 8.x的主要内容,如果未能解决你的问题,请参考以下文章