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

178
Vistas
How to get the sum of multiplied array keys from an array

A cargo has many orders. An order has a quantity and a price. For every order in a cargo, I want to return the sum of quantity * price as a single value.

A cargo collection returns data as:

{
    "data": {
        "cargo_id": 4,
        "name": "Cargo Name",
        "qty": "366200.00",
        "cost": 140,
        "product_id": 1,
        "product": {
            "id": 1,
            "name": "Sample Product"
        },
        "orders": [
            {
                "id": 1,
                "cargo_id": 4,
                "qty": 14200,
                "price": "500"
            },
            {
                "id": 4,
                "cargo_id": 4,
                "qty": 12000,
                "price": "500"
            },
            {
                "id": 6,
                "cargo_id": 4,
                "qty": 5600,
                "price": "500"
            }
        ],
        "comments": "sample",
    }
}

I have tried using an Eloquent Accessor in the Cargo class as:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Cargo extends Model
{
    protected $guarded = [];

    protected $appends = [
        'product_margin'
    ];

    public function orders() {
        return $this->hasMany(Order::class);
    }

    public function getProductMarginAttribute() {
        $orders = $this->orders();
        $total = 0;

        foreach ($orders as $order) {
            $total += $order['qty'] * $order['price'];
        }

        return $total;
    }
}

But product_margin returns 0. How can I get this working?

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

0

This $this->orders() return hasmany relationship data. To get the item collection from relationship data you should use get(). Update the code in your Cargo modal.

    public function getProductMarginAttribute() {
        $orders = $this->orders()->get();
        $total = 0;

        foreach ($orders as $order) {
            $total += $order['qty'] * $order['price'];
        }

        return $total;
    }
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