where('store_id', $storeId) ->where('is_bundle', true) ->with(['bundleItems.product', 'bundleItems.variant']) ->get() ->each(function (Product $bundle): void { $stock = self::for($bundle); if ($bundle->stock !== $stock) { $bundle->stock = $stock; $bundle->saveQuietly(); } }); } /** * How many of this bundle can be sold now. */ public static function for(Product $bundle): int { if ($bundle->bundleItems->isEmpty()) { return 0; } return (int) $bundle->bundleItems ->map(fn (BundleItem $item) => intdiv(max(0, $item->stock()), max(1, $item->quantity))) ->min(); } }