2

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.

3
  • In case you're using the array session driver, that I'm afraid that's the only option. Commented May 10, 2015 at 12:13
  • What other driver can I use? Thanks! Commented May 10, 2015 at 12:18
  • Hey there. Out of curiosity, is your itemId auto-incrementing? If it is, how did you achieve it? Commented Aug 6, 2015 at 2:48

1 Answer 1

2

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"
  }
]
Sign up to request clarification or add additional context in comments.

5 Comments

@peterm I'm trying something similar but I'm getting "Trying to get property of non-object" error on line ` $item->itemQuantity = $item->itemQuantity * 2; `
@peterm yes, I'm just not sure why it happens since my code is based on yours: foreach(Session::get('cart.program') as $item){ if ($item->id == '1xxx') { $item->segment_weekday = '9'; break; } }
@peterm var_dump(Session::get('cart.program')): array (size=2) 0 => array (size=1) 'id' => string '1' (length=1) 1 => array (size=1) 'id' => string '1xxx' (length=4)
@peterm Thanks for your help. I can access array members, just can't figure out how to pass $item by reference &$item to save back to session.
@peterm Created a new question at stackoverflow.com/questions/31887608/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.