phplaravellaravel-8laravel-collection

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.

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.

Solution

  • 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();