Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AydenWH's avatar

Update HTTP Session Record

I want to update the HTTP session record if the record is existing.

Example like when user click add to cart of certain item, and the item id belongs to 1 which is already existing in this array.

So instead of adding a new one array, I would like to update the quantity only.

Is that possible?

array:2 [▼
  0 => array:1 [▼
    0 => array:4 [▼
      "id" => "1"
      "name" => "Discovery"
      "quantity" => 1
      "price" => "4990"
    ]
  ]
  1 => array:1 [▼
    0 => array:4 [▼
      "id" => "2"
      "name" => "Discovery - 2"
      "quantity" => 1
      "price" => "9990"
    ]
  ]
]
0 likes
7 replies
mikefolsom's avatar
Level 21

If you are just storing the cart as a multidimensional array, I would suggest using the product ID as the array key, so in the above code snippet, your keys would be 1 and 2 rather than 0 and 1. And flatten it by one level.

Then when an item is added you can test array_key_exists and act accordingly:

// Retrieve the product ID from the request
$productId = request('product_id');

// Retrieve the cart from the session
$cart = session()->get('cart');

// Update quantity if item already exists
if (array_key_exists($productId, $cart)) {
    $cart[$productId]['quantity'] += 1;
} else {
    // Add new product to cart
    $cart[$productId] = [
        'id' => $productId,
        'quantity' => 1,
        // ...
    ];
}

// Store cart back to session
session(['cart' => $cart]);

Note this is a very naïve implementation. In real world usage, you would most likely have a cart object stored in the session with the ability to specify quantities explicitly, remove items, etc.

1 like
AydenWH's avatar

@mikefolsom

Morning Mike.

I am using $request->session()->push() method to add the new cart item.

This is why the cart array is starting from 0.

I am implementing this cart feature for real life usage, but I don't really understand what do you mean by ability to specify quantities explicitly etc.

AydenWH's avatar

@mikefolsom

Do you mean something like this?

/** 
  *     1. Clear Session
  *     2. Place ID into session
  *     3. Place quantity under ID
  **/

session()->flush();
session()->put(1);
session(['1.quantity' => ($cart[1]['quantity'] = 10)]);

Output

array:1 [▼
  1 => array:1 [▼
    "quantity" => 10
  ]
]

Managed to solve and come out with a solution.

$cart_item = [
    'name' => $request->name, 
    'quantity' => 1, 
    'price' => $request->price
];

session()->put($request->id);
session([$request->id => $cart_item]);
mikefolsom's avatar

I mean most carts will have the ability to choose a quantity. If someone wanted 10 of an item, they would not expect to have to hit "add to cart" 10 times. I'm suggesting you might want the session's 'cart' key contents to look something like this, modifying that key with every request rather than using push().

$cart = [
    1 => [
        'id'       => '1',
        'name'     => 'Discovery',
        'quantity' => 1,
        'price'    => '4990',
    ],
    2 => [
        'id'       => '2',
        'name'     => 'Discovery - 2',
        'quantity' => 10,
        'price'    => '9990',
    ],
    6 => [
        'id'       => '6',
        'name'     => 'Discovery - 6',
        'quantity' => 5,
        'price'    => '11990',
    ],
];
AydenWH's avatar

@mikefolsom

For my case, we have limited product line and thus quantity is not high. Because this product is accessory, stationary or apparel.

mikefolsom's avatar

@Tyris Fair enough. I still believe that storing a single array as your session's "cart" variable will make it easier to reason about. As in my first example:

  1. Check the session to see if the "cart" key exists if (session()->has('cart')). If not, create it.
  2. Check to see if the array key (corresponding to the product ID) is set
  3. If the array key is set, update the quantity; if not, add a new item to the array, using the product ID as the key
  4. Save that array back to the same session key

Cheers!

AydenWH's avatar

@mikefolsom

After struggling few ten minutes, I managed to come out with a solutions. Thanks a lot.

$cartItem = $request->session()->get('cart_item');

if ($cartItem) {
    if (array_key_exists($request->id, $cartItem)) {
        $cartItem[$request->id]['quantity'] += 1;

        session()->put('cart_item.' . $request->id . '.quantity', $cartItem[$request->id]['quantity']);
    } else {
        $cart_item = [
            'id' => $request->id,
            'name' => $request->name, 
            'quantity' => 1, 
            'price' => $request->price
        ];
        session()->put('cart_item.' . $request->id, $cart_item);
    }
} else {
    $cart_item = [
            'id' => $request->id,
            'name' => $request->name, 
            'quantity' => 1, 
            'price' => $request->price
        ];
    session()->put('cart_item.' . $request->id, $cart_item);
}

Please or to participate in this conversation.