简体   繁体   中英

How to update a single value in a Laravel Session Array?

I have a Session array like this:

[
    {
        "itemId": "1",
        "itemQuantity": "3",
        "itemName": "Item_name1"
    },
    {
        "itemId": "2",
        "itemQuantity": "2",
        "itemName": "Item_name2"
    }
]

How can I update the quantity of a single item if I know the itemId ?

I know that one way of doing this would be to fetch the whole array, loop through the array, make the updates and 'put' the entire array back into the session. Is this the only way?

I'm a beginner. Please help out. Thanks.

Objects are passed by reference so you can simply do this.

foreach(Session::get('cart') as $item) {
    if ($item->itemId == '2') { // say we  want to double the quantity for itemId 2
        $item->itemQuantity = $item->itemQuantity * 2;
        break;
    }
}
dd(Session::get('cart'));

Output:

array:2 [▼
  0 => {#162 ▼
    +"itemId": "1"
    +"itemQuantity": "3"
    +"itemName": "Item_name1"
  }
  1 => {#163 ▼
    +"itemId": "2"
    +"itemQuantity": 4  <<--- the quantity has been doubled
    +"itemName": "Item_name2"
  }
]

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