0

To simplify the problem, as I am iterating through the array of objects returned by the eloquent query, when I attempt to change one of it's property it seems to be changing of all their properties.

Assuming fruits is the data returned from the eloquent query

var fruits =[{name:apple,nested_relationship:{price:$5},{name:pear,{price:$6},{name:grape}]

foreach ($fruits as fruit){
  if($fruit->name == 'apple'){
     $fruit->nested_relationship->color = 'red';
  }
  elseif($fruit->name == 'grape'){
     $fruit->nested_relationship->color = 'green';
  }
}

The final result seems to be [{name:'apple',nested_relationship:{price:$5,color:'green'}},{name:pear,nested_relationship:{price:$5,color:'green'}},},{name:'grape'}]

Can someone please tell me what is going on?

Yeo Bryan
  • 331
  • 4
  • 24
  • Can't find the problem here. I think we need to have a look in your original code. – ya-cha Oct 06 '21 at 09:22
  • @ya-cha i made some edits to better reflect the situtation. Could the nested relationship be what is causing the issue? – Yeo Bryan Oct 06 '21 at 09:28
  • Is nested_relationship maybe both time the same relation? – ya-cha Oct 06 '21 at 10:11
  • @ya-cha what do you mean? and this https://stackoverflow.com/questions/69463617/looping-and-changing-value-of-nested-eloquent-relationship might be a better representation of the problem, please help me out if possible – Yeo Bryan Oct 06 '21 at 10:11
  • and @ya-cha if the relation is the same, is it possible to edit one without editing the other – Yeo Bryan Oct 06 '21 at 10:17
  • @YeoBryan based on your comment above and in response to Muhammad's answer below, it sounds like you need to update your question so that the code properly represents the problem. – TTT Oct 06 '21 at 15:02

1 Answers1

0

Try this solution:

Use setAttribute() to add new atribute.

var fruits =[{name:apple,nested_relationship:{price:$5},{name:pear,{price:$6},{name:grape}]

foreach ($fruits as $fruit){
  if($fruit->name == 'apple'){
     $fruit->nested_relationship->setAttribute('color', 'red');
  }
  elseif($fruit->name == 'grape'){
     $fruit->nested_relationship->setAttribute('color', 'green');
  }
}
Shahid Rasheed
  • 371
  • 4
  • 10
  • Sadly it doesnt work, I have a feeling its changing the value of the reference fruit but when error_logging the $fruits, the change is reflected wrongly – Yeo Bryan Oct 06 '21 at 09:46
  • what is your expected and current output ? – Shahid Rasheed Oct 06 '21 at 10:04
  • https://stackoverflow.com/questions/69463617/looping-and-changing-value-of-nested-eloquent-relationship. This might be a better example of the problem, please do help me out – Yeo Bryan Oct 06 '21 at 10:10