Changing an attibute of Laravel Eloquent collection changes every reference

Viewed 69

Here's my scenario. I have a relationship between subscription and product. Every subscription belongs to some product and I have defined relationships.

Now if I do this: Subscription::with(['product', 'address'])->get(); I will get all subscriptions with product.

Product have attibutes like shipping_price, price etc.

Now if I change shipping_price of a product within a subscription, it changes shipping_price for that product inside all subscriptions (This comes in handy manier times but this time I dont want this change to reflect everywhere).

For example:

$subscriptions = Subscription::with('product')->get();
foreach ($subscriptions as $item) {
   $item->product->shipping_price = ShippingService::getShippingPrice($item->product->key, $item->product->shipping_price, $item->address->zip);
}

This will change shipping_price for every product having same ID within those subscriptions.

My requirement is to stop this behavior at this one place. So if I change one attribute, it doesnt change others.

I know one way to query again with loop and dont get products using eager loading but that will be slow.

Thanks.

1 Answers
Related