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

pavlen's avatar

Laravel 8 session problem - overwriting existing session key

Hi, I have problem with sessions in Laravel 8 .

When try :

$request->session()->put('test', 2);

I get good store result:

"test" => 2

Now, when I try to store another value:

$request->session()->put('test2', 3);

I expect to get this result :

"test" => 2, "test2" => 3

But I only get this:

"test2" => 3

I lost my first data from session ?!

  • I clear cache&cookies from browser, also I do this: rm -f storage/framework/sessions/

Any idea ? Thanks

0 likes
5 replies
Sinnbeck's avatar

Can you show the actual code where you set it and retrieve it?

pavlen's avatar

@Sinnbeck Hi, thanks for a time.

Here is my code when I put to a session

public function addToCart(Request $request) { $product = Product::findOrFail($request->get('product'));

$cake = [
    'title' => $request->get('title'),
    'note' => $request->get('note'),
    'shape' => $request->get('shape'),
    'price' => $request->get('price'),
];
$request->session()->put("cart.cake." . $product->slug, $cake);

return redirect()->route('cart');

}

I have 2 cakes, the first has a url-slug mickey-mouse and the second a mini-mouse. When I try to add the first cake to the cart, the session looks like this: [ "cart" => [ "cake" => [ "mickey-mouse" => [ 'title' => 'some data', 'note' => 'some data', 'shape' => 'some data', 'price' => 'some data', ] ] ] ]

But when I try to add another cake to the cart, the session looks like this: [ "cart" => [ "cake" => [ "mini-mouse" => [ 'title' => 'some data', 'note' => 'some data', 'shape' => 'some data', 'price' => 'some data', ] ] ] ]

But it should look like this: [ "cart" => [ "cake" => [ "mickey-mouse" => [ 'title' => 'some data', 'note' => 'some data', 'shape' => 'some data', 'price' => 'some data', ], "mini-mouse" => [ 'title' => 'some data', 'note' => 'some data', 'shape' => 'some data', 'price' => 'some data', ] ] ] ]

And on the cart page, when I try to list everything from the session, I only have only mini-mouse cake in the session.

Sinnbeck's avatar

I am curious by you cart build up? Wouldnt you just have a single key called 'cart' that holds all items?

$request->session()->push("cart", $cake);

$request->session()->get("cart"); //all items in the cart
pavlen's avatar

@Sinnbeck hi again.. I have a structural problem, your logic is ok, but I have different "products" that can't be stored in the same table(I have a unique table for cakes, a unique table for cookies), as is a good practice..

I must do on this way because I have a really complicated request on the shop page....

I am just curious why is it missing store data?

Please or to participate in this conversation.