I have 5 tables: sales_orders, product_sales_order (pivot table between sales_orders and products), products, shipment, and product_shipment (pivot table between shipment and products).
SalesOrder.php
class SalesOrder extends Model
{
public function products()
{
return $this->belongsToMany(Product::class)
->using(ProductSalesOrder::class)
->withPivot(['qty', 'price']);
}
public function shipments()
{
return $this->hasOne(Shipment::class);
}
}
ProductSalesOrder.php
class ProductSalesOrder extends Pivot
{
public function getSubTotalAttribute()
{
return $this->qty* $this->price;
}
}
Shipment.php
class Shipment extends Model
{
public function salesOrder()
{
return $this->belongsTo(SalesOrder::class);
}
public function products()
{
return $this->belongsToMany(Product::class)
->withPivot(['qty']);
}
}

Here what I want to achieve
Since 1 sales_order able to ship the product several times, I need to know how many products that already shipped before. And when I create new shipment, I need to limit the maximum qty that can be send at that time.
In this case, sales_order has 2 products with order qty 100 pcs each. Yesterday, I create 2 shipment which is 25 pcs and 50 pcs for product A. When I want to create new shipment for today, I can only send 25 pcs for product A and 100 pcs for product B.
I've tried my own way, using nested foreach and store the value that I want to an array. But is it possible to sum the qty inside product_shipment and compare it with the qty that has been ordered using eloquent?