I wanted to change my collection set to a new variable, but it changed the original.
I thought this was a JavaScript issue and PHP was referring to value.
How do I set my collection to a new variable, which I can alter without changing the original collection.
JavaScript
x
$pets = Pet::all();
$tmp = $pets;
$tmp->pop();
$pets->dd(); // This value also has it's last item removed.
I’m using this workaround for now:
JavaScript
$tmp = $pets->map(function (item) {
return $item;
});
$tmp->pop();
$pets->dd(); // This value is now unchanged.
Advertisement
Answer
Try using clone
JavaScript
$pets = Pet::all();
$tmp =clone $pets;
$tmp->pop();
$pets->dd();
If you like to use collection then add method to collection using macro in AppServiceProvider
boot method
JavaScript
public function boot()
{
Collection::macro('clone', function() {
return clone $this;
});
}
then you can do the following
JavaScript
$pets = Pet::all();
$tmp =$pets->clone();
$tmp->pop();
$pets->dd();