isEmpty() || $products->isEmpty()) { return; } Purchase::factory(50)->create()->each(function ($purchase) use ($users, $products) { $itemsCount = rand(1, 5); $total = 0; for ($i = 0; $i < $itemsCount; $i++) { $product = $products->random(); $quantity = rand(1, 10); $unitPrice = rand(10000, 500000); $totalPrice = $quantity * $unitPrice; PurchaseItem::create([ 'purchase_id' => $purchase->id, 'user_id' => $users->random()->id, 'product_id' => $product->id, 'quantity' => $quantity, 'unit_price' => $unitPrice, 'total_price' => $totalPrice, 'created_at' => $purchase->created_at, ]); $product->increment('stock', $quantity); $total += $totalPrice; } $purchase->update(['total' => $total]); }); } }