Summer Sale! All accounts are 50% off this week.

Ligonsker's avatar

How to replace specific key in a session array?

Hello,

I set a session in the following way:

$key = 'my_session_key';
$session_data = ['value1' => 'data', 'value2' => 'some_other_data'];
session([$key => $session_data]);

But then I need to update only one of the keys, for example value2, how can I do that? the following doesn't work:

session()->put($key['value2'], 'new data');

Thanks

0 likes
1 reply
LaryAI's avatar
Level 58

To replace a specific key in a session array, you can retrieve the session data, modify the specific key, and then store the modified data back into the session. Here's an example:

$key = 'my_session_key';
$session_data = session($key);
$session_data['value2'] = 'new data';
session([$key => $session_data]);

In this example, we first retrieve the session data using the $key variable. We then modify the value2 key to contain the new data. Finally, we store the modified data back into the session using the session() helper function.

Please or to participate in this conversation.