Hkm Sadek
Hkm Sadek

Reputation: 3209

How to override property value in a collection?

I am trying to override the property value using a foreach loop.

Here is what I am trying:

$runningLeagues = $this->getLeagueListing('running', $clubIds);
// chanage city
foreach($runningLeagues as $d){
    $d->club->city = $d->city;
}
return $runningLeagues; 

But if I just return from the loop I get the correct result. So the below code works:

foreach($runningLeagues as $d){
    $d->club->city = $d->city;
    return $d; // it shows the overridden city. It works.
}

I have city property inside club object and outside object as well. I want to change the city inside the club object from the outside city property value.

It keeps the values same. It doesn't change.

Update

It seems it updates with the last item. So if last properties city is 'ss' it will add 'ss' in all the properties.

Any idea whats happening?

Upvotes: 0

Views: 190

Answers (1)

IndianCoding
IndianCoding

Reputation: 2683

Try this:

First. Laravel collection each() method:

$runningLeagues->each(function ($d) {
    $d->club->city = $d->city;
});

Second. By collection index:

foreach($runningLeagues as $k => $d) {
    $runningLeagues[$k]->club->city = $d->city;
}

Upvotes: 1

Related Questions