*/ class EggCollectionFactory extends Factory { protected $model = EggCollection::class; public function definition(): array { $dateTime = $this->faker->dateTimeBetween('-1 month', 'now'); return [ 'production_date' => $dateTime, 'total_eggs' => 0, 'notes' => $this->faker->optional(0.4)->sentence(), ]; } public function configure() { return $this->afterCreating(function (EggCollection $collection) { $chickens = Chicken::where('status', 'ACTIVE') ->inRandomOrder() ->take(20) ->get(); if ($chickens->isEmpty()) { $chickens = Chicken::factory()->count(20)->create(); } $itemCount = $this->faker->numberBetween(5, min(20, $chickens->count())); $selectedChickens = $chickens->shuffle()->take($itemCount); $totalEggs = 0; foreach ($selectedChickens as $chicken) { $eggsCount = $this->faker->numberBetween(0, 2); if ($eggsCount <= 0) { continue; } EggCollectionItem::create([ 'egg_collection_id' => $collection->id, 'chicken_id' => $chicken->id, 'eggs_count' => $eggsCount, ]); $totalEggs += $eggsCount; } $collection->update(['total_eggs' => $totalEggs]); }); } }