Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

272
Vistas
Changing an attibute of Laravel Eloquent collection changes every reference

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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I would add a custom property "real_shipping_price" to this product Model with an accessor getRealShippingPriceAttribute (using your ShippingService).

See https://laravel.com/docs/5.3/eloquent-serialization#appending-values-to-json for example.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda