Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda