You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Not all collection methods return a new collection instance and some are destructive or additive.
To prevent modifying collections that are used in later code too when only a temporary copy is needed for the current operation, a copy() and clone() method would be very helpful:
foreach ($collection->copy()->push('new')->reverse() as$item)
// or for cloning objects in collectionsforeach ($collection->clone()->push('new')->reverse() as$item)
Using PHP clone keyword doesn't solve the problem easily because a relation can also return NULL instead of a collection. When using clone $model->relation on NULL, a fatal error will be the result. Instead, we can use:
foreach ($model->relation?->copy()?->push('new')?->reverse() ?? [] as$item)
// or for cloning objects in collectionsforeach ($model->relation?->clone()?->push(new \stdClass)?->reverse() ?? [] as$item)
copy() creates only a new collection object while clone() clones all objects within the collection too.
The PHP Map package implements them too:
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Not all collection methods return a new collection instance and some are destructive or additive.
To prevent modifying collections that are used in later code too when only a temporary copy is needed for the current operation, a copy() and clone() method would be very helpful:
Using PHP
clone
keyword doesn't solve the problem easily because a relation can also return NULL instead of a collection. When usingclone $model->relation
on NULL, a fatal error will be the result. Instead, we can use:copy()
creates only a new collection object whileclone()
clones all objects within the collection too.The PHP Map package implements them too:
Beta Was this translation helpful? Give feedback.
All reactions