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

minjon's avatar
Level 15

How to push an array into a session

I would like to create a session cart with an array of items where array_keys would be items ids rather than indexes.

This is the code I have created:

<?php
$item = [
    $id => [
        'id' => $id,
         'qty' => $qty
     ]
 ];

Session::push('cart', $item);
?>

This is the output I've got:

Array
(
    [0] => Array
    (
        [$id] => Array
        (
            [id] => $id
            [qty] => $qty
        )
    )
)

This is the output I would like to get:

Array
(
    [$id] => Array
    (
        [id] => $id
        [qty] => $qty
    )
)

Is it somehow possible?

0 likes
7 replies
bugsysha's avatar

Fetch items from the DB and key them with this:

$items = \App\Item::all()->keyBy('id');
minjon's avatar
Level 15

@prasinoulhs When I use Session::put('cart', $item) and add one item at a time, the added item replaces the previous one - so there is no an array of items but only one item stored in the session.

prasinoulhs's avatar

If you want to add a single item

$item = [
  'id' => $id,
  'qty' => $qty
];

Session::push('cart', $item);

$items = Session::get('cart');

if you want to add multiple items you either call push for each one, or get the items from the session merge them with the new items and put them back.

1 like
shez1983's avatar

maybe check out a library or a package that does the cart/shopping basket for you? why re-invent the wheel

minjon's avatar
Level 15

@shez1983 Thanks for your suggestion. However, it's as if I would think with other person's head. I still prefer to use my own.:)

shez1983's avatar

@minjon when you use LARAVEL you already think with other person's head... so i suggest you use pure PHP (Which again is thinking with someone's head)..

most packages are stable, have documentation & using them should cut down the amount of time it takes for you to create something rather then you inventing your own untested solution!..

just my 3 cents..

Please or to participate in this conversation.