dress/database/seeders/PurchaseSeeder.php

53 lines
1.4 KiB
PHP

<?php
namespace Database\Seeders;
use App\Models\Product;
use App\Models\Purchase;
use App\Models\PurchaseItem;
use App\Models\User;
use Illuminate\Database\Seeder;
class PurchaseSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$users = User::all();
$products = Product::all();
if ($users->isEmpty() || $products->isEmpty()) {
return;
}
Purchase::factory(10)->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,
]);
$product->increment('stock', $quantity);
$total += $totalPrice;
}
$purchase->update(['total' => $total]);
});
}
}