php - Pushing to array session - Laravel 8.x
Get the solution ↓↓↓I want to store in a session array a shopping cart. I'm trying to do this:
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);
}
}
Output:
[
0 => [
"id" => "12"
"quantity" => 1
]
]
But when I call another time the function add() it replace the array like so:
[
0 => [
"id" => "20"
"quantity" => 1
]
]
Desired output:
[
0 => [
"id" => "12"
"quantity" => 1
]
1 => [
"id" => "20"
"quantity" => 1
]
2 => [
"id" => "27"
"quantity" => 1
]
]
Answer
Solution:
This will get you sorted as long as you carry the cart id to every function you wish to work with the cart. below is the add product to cart session
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 !!');
}
Answer
Solution:
It is probably becauseshopping_cart
is an already defined key. So it will overwrite data with that key. The best thing you can do is create a unique item with the ID in thatshopping_cart
object. Something like;
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);
}
Now you're also able to get/pull data from the session based on theshopping_cart
ID/key
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to undefined function illuminate\encryption\openssl_cipher_iv_length()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.