简体   繁体   中英

how to add new array to an global session array in laravel?

I want to add new arrays to an global session array in laravel 5.6

The global session is cart . I want add items to this array.

I try this:

for first time:

$item = ['key' => 'val1'];

session()->push('cart', $item);
dd(session()->get('cart'));

It works:

array:1 [▼
  0 => array:1 [▼
    "key" => "val1"
  ]
]

Now, I change $item = ['key' => 'val1']; to $item = ['key' => 'val2']; and refresh the page again.

but it remove "key" => "val1" and return this:

array:1 [▼
      0 => array:1 [▼
        "key" => "val2"
      ]
    ]

what's my wrong?

So, everything is correct here. First you add val1 under key . It is stored on SESSION. Next you replace val1 with val2 . You can either add val2 under key2 , or use dot notation:

session()->push('cart.key', `val1`);
session()->push('cart.key', `val2`);
dd(session()->get('cart'));

for more details https://laravel.com/docs/7.x/helpers#method-session

session()->get('key');

session()->put('key', $value);

session(['chairs' => 7, 'instruments' => 3]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM