Skip to content
Advertisement

Laravel – how to copy collection to a new variable

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.

$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:

$tmp = $pets->map(function (item) {
    return $item;
});
$tmp->pop();
$pets->dd(); // This value is now unchanged.

Advertisement

Answer

Try using clone

$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

public function boot()
{
      
   Collection::macro('clone', function() {
       return clone $this;
    });

}

then you can do the following

$pets = Pet::all();
$tmp =$pets->clone();
$tmp->pop();
$pets->dd();
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement