-1
$arrList = [];
foreach ($product as $val) {
    $arrList[]['name'] = $val->name;
    $arrList[]['quantity'] = $val->quantity;
}

return response()->json($arrList);

I am a PHP newbie, so I'm not sure how to handle this. I want the name and quantity to be in the same array.

To the Vue side get the same result?

(2) [{…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer]
0:
name: iphone
quantity: 100
1:
name: samsung
quantity: 130
1
  • I do not understand your question, can you explain more please ? Commented Jul 30, 2021 at 4:09

1 Answer 1

2

Just change the two lines within the foreach loop like:

$arrList = [];
foreach ($product as $val) {
    $arrList[] = ['name' => $val->name, 'quantity' => $val->quantity];
}

return response()->json($arrList);

This will ensure that both the name and quantity are inserted in the same array and at the same index.

And in javascript you can traverse through the json and then use the variables as required.

data.forEach(function(element) {
    const name = element.name;
    const quantity = element.quantity;
});
1
  • 1
    If you're grabbing the data via an API, you should check out using resources. Will change your life! Commented Jul 30, 2021 at 4:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.