Skeletor
Skeletor

Reputation: 3403

How to add additional (multiple) values to session without overwriting the existing array?

When I try to add additional data to an session array it overwrites the old ones. Is there a way to add multiple values to session array without overwriting the old one or have I to use push one by one?

Here for example:

session()->put([
  'parent'=>[
     'name'=>'jhon', 
     'surname'=>'doe', 
  ] 
]); 

Now with session()->all() I get:

[
   "parent" => [
      "name" => "jhon",
      "surname" => "doe",
   ],
]

When I want to add additional values with put for example:

session()->put([
  'parent'=>[
     'gender'=>'male', 
     'phone'=>'000000', 
  ] 
]); 

No I get this with session()->all():

[
   "parent" => [
     "gender" => "male", 
     "phone" => "000000",
   ],
]

But I want:

[
   "parent" => [
      "name" => "jhon",
      "surname" => "doe",
      "gender" => "male", 
      "phone" => "000000",
   ],
]

So how can I add additional (multiple) data to an existing session array without touching the old ones?

Upvotes: 0

Views: 923

Answers (3)

Skeletor
Skeletor

Reputation: 3403

Thank to @AlexeyMezenin and @GautamPatadiya answers I found this way which looks very convenient to me. Please correct if this seems wrong to you or there is a better way you konw.

session()->put([
  'parent'=>[
     'name'=>'jhon', 
     'surname'=>'doe', 
  ] 
]); 

Then just add itself to the new array like:

session()->put([
  'parent'=>[
     'gender'=>'male', 
     'phone'=>'000000', 
  ] + session('parent');
]); 

Upvotes: 0

jaysingkar
jaysingkar

Reputation: 4435

You can use session()->push() method as given here
For e.g.
1) Put the data first time using session()->put()

session()->put([
  'parent'=>[
     'name'=>'jhon', 
     'surname'=>'doe', 
  ] 
]);

2) Now Push the data you want to add using session()->push()

session()->push('parent',[
   'gender'=>'male', 
   'phone'=>'000000', 
]);

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

You can read data first, modify it and save it again. Just an example:

$data = session('parent');

$data['gender'] = 'male';
$data['phone'] = '000000';

session(['parent' => $data]);

Upvotes: 2

Related Questions