'Return new collection without modifying original collection

I have a Laravel collection and I want to modify one of its property value to negative integer. For this I am using the collection map method but it also modifying the original collection.

My code:

$modified_revenue_data = $revenue_data->map(function ($item) {
    if ($item->is_claw_back == 1 && $item->claw_back_date != null) {
        return $item->revenue = $item->revenue * -1;
    }

    return $item;
});

I want to store the new collection into $modified_revenue_data but $revenue_data is also modified.

What would be the correct way of doing it without modifying the original collection?



Solution 1:[1]

It doesn't update the original collection:

$original = collect([1, 2, 3, 4, 5]);

$modified = $original->map(function ($el) {
     return $el * 2; 
});

dd($modified);
=> Illuminate\Support\Collection {#3726
     all: [
       2,
       4,
       6,
       8,
       10,
     ],
   }
dd($original);
=> Illuminate\Support\Collection {#3743
     all: [
       1,
       2,
       3,
       4,
       5,
     ],
   }

This behaviour is also stated in the documentation:

map()

...

Like most other collection methods, map returns a new collection instance; it does not modify the collection it is called on. If you want to transform the original collection, use the transform() method.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1