Updating previous Session Array Laravel
19,359
Solution 1
$items = Session::get('items', []);
foreach ($items as &$item) {
if ($item['item_id'] == $id) {
$item['item_quantity']--;
}
}
Session::set('items', $items);
Solution 2
If you have nested arrays inside your session array. You can use the following way to update the session: $session()->put('user.age',$age);
Example
Supppose you have following array structure inside your session
$user = [
"name" => "Joe",
"age" => 23
]
session()->put('user',$user);
//updating the age in session
session()->put('user.age',49);
if your session array is n-arrays deep then use the dot (.) followed by key names to reach to the nth value or array, like session->put('user.comments.likes',$likes)
Comments
-
Martney Acha almost 2 years
I have an issue on how can I update my Previous array ? What currently happening to my code is its just adding new session array instead of updating the declared key here's my code:
foreach ($items_updated as $key => $added) { if ($id == $added['item_id']) { $newquantity = $added['item_quantity'] - 1; $update = array( 'item_id' => $items['item_id'], 'item_quantity' => $newquantity, ); } } Session::push('items', $updated);
-
Martney Acha almost 10 yearsWhat would I need is saving again with its same Item_Id but with new Quantity so I think Session::forget('key') is not the solution.
-
Martney Acha almost 10 yearsIt works Thank you Joseph!!! but what does $items as &$item ? I want to understand it thank you.
-
Joseph Silber almost 10 yearsThe ampersand means that it's a reference to the individual item array, not a copy. If you were to do
$items as $item
, the$item
variable would hold a copy of the item in the$items
array, and decreasing itsitem_quantity
property would have no effect on the item in the$items
array.