One method that is important do Illuminate/Collection have is clone(), this method generate a copy of the current collection.
Can anyone make some comments here why or why not this is a bad idea ?
Thanks.
$collection = collect();
$clone = $collection->clone();
// or
$clone = clone $collection;
Why are you not able to use the $clone = clone $collection; example?
For me that works:
$collection = collect([1, 2, 3]);
dd(
$collection,
clone $collection
);

Or is this a feature request?
If it is, its pretty simple to complete with a macro;
\Illuminate\Support\Collection::macro('clone', function() {
return clone $this;
});
@alexbowers this works with simple internals, but test this with objects that are passed has references, the clone method obviously don't copy the objects, only the references, is correct to copy all object's in the collection or mantain the references to them original objects ?
I'd say if you were cloning a reference, you'd expect it to still reference the same thing. A clone should be an exact replica.
I'd say if you were cloning a reference, you'd expect it to still reference the same thing
That's not the definition of cloning.
Cloning a collection will give a shallow clone. Are you asking for a way to do a deep clone?
You could always traverse the object and clone each item individually if it is itself an object. Doing this recursively would be a deep clone I guess
@GrahamCampbell @alexbowers yes deep-copy is what I mean, any chance to have some native stuff in Laravel for this ? or is more application like feature ?
Well I'm going to close this Issue since it's not a bug report, I suggest that you open a PR with the suggested changes or open an issue on the internals repository, it's where we keep all our discussions & feature requests.
Thanks for the suggestion though :)
Most helpful comment
Why are you not able to use the
$clone = clone $collection;example?For me that works:
Or is this a feature request?
If it is, its pretty simple to complete with a macro;