1

I have my data like:

data: [,…]
    0: {name: "Product One", price: "15000", quantity: 2, attributes: {attr: {name: "weight", value: "35"}},…}
        attributes: {attr: {name: "weight", value: "35"}}
        conditions: [{name: "blue", value: 0}, {name: "L", value: 0}]
        name: "Product One"
        price: "15000"
        quantity: 2

I need to add id into each array of my data like:

data: [,…]
    0: {name: "Product One", price: "15000", quantity: 2, attributes: {attr: {name: "weight", value: "35"}},…}
        attributes: {attr: {name: "weight", value: "35"}}
        conditions: [{name: "blue", value: 0}, {name: "L", value: 0}]
        name: "Product One"
        price: "15000"
        quantity: 2
        id: 10 // added id

Screenshot

Here is how my database looks like:

one

Code

Currently just getting my cart_data column, need to add column id as well.

$items2 = CartStorage::where('user_id', $user->id)->get();

$items = [];
foreach($items2 as $item){
  $items[] = json_decode($item['cart_data']); 
}

1 Answer 1

2

Can be by creating a var and add it there like so:

$items2 = CartStorage::where('user_id', $user->id)->get();

$items = [];
foreach($items2 as $item){
  $decodedItems       = json_decode($item['cart_data'], true);
  $decodedItems['id'] = $item['id'];
  $items[]            = $decodedItems;
}
Sign up to request clarification or add additional context in comments.

6 Comments

it says Cannot use object of type stdClass as array
I've added true as seconde param in json_decode to make it an array.
Thank you, this works also the one before this $decodedItems->id works as well (without true)
That is also an option. Even better would be using Collections.
@Ersoy if you check this package for instance or any other cart package they all use same method as storing cart data into json array, the diffrence is because i am using VueJs I do not have access to sessions on API requests so I've made my own database table version of cart implementation. You might be right but I don't think there is any issue of storing data into json. Also this ID I just need it in order to remove/update items from database, shouldn't actually be in cart_data column.
|

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.