@foreach ($stocks as $productId => $stockGroup) @php // Find the first stock with qty > 0 $availableStock = $stockGroup ->where('qty', '>', 0) ->sortByDesc('created_at') ->first(); if (!$availableStock) { $availableStock = $stockGroup->first(); } $totalQty = $stockGroup->sum('qty'); $product = $availableStock ? $availableStock->product : $stockGroup->first()->product; $unitPrice = $availableStock ? $availableStock->unit_price : 0; $stockId = $availableStock ? $availableStock->id : $stockGroup->first()->id; @endphp @if (!empty($product)) @endif @endforeach