How can I change the property that belongs to one of returned entry’s relationship without affecting the other?
The example query below returns two entries with each having their own set of relationship attached to them
$tttt = AppManualTicket::where(function ($checkUser) {
$checkUser->where("id",'=',408257)
->orWhere("id",'=',408258);
})->with(['same_manual_ticket_group','same_manual_ticket_group.user','same_manual_ticket_group.completed','same_manual_ticket_group.initiator','same_manual_ticket_group.prior_rerouted_ticket','same_manual_ticket_group.ticket_flow_order'])->get();
I expect the code below to change the first entry’s relationship id to ‘FFFF’ and the second entry’s relationship id to ‘BBBB’ however they are both being changed to ‘BBBB’.
$tttt[0]['same_manual_ticket_group'][0]['id']='FFFF';
$tttt[1]['same_manual_ticket_group'][0]['id']='BBBB';
3
Answers
You can use the map function of collection or convert $ttt to array and then assign value
It’s better to use Laravel’s Collection class built-in function. Here is an example using
map
function that might suit your case:As others have pointed out, you’d have to first turn the collection into an array and then modify the key.
This happens probably because they are referencing the same model, so they point to the same data.
When you dump the variable, you can see a number next to each class. For example
If what you are trying to modify shares numbers, then it’s referencing the same object
An easy way to see this is by running the following in
php artisan tinker
same reference number, both values update. When transforming to an array, you don’t have to deal with that. Another possibility (if you know exactly which values to change) is to
clone
the objects. Here’s how that would look in ourphp artisan tinker
exampleApplied to this case: