xtremer360
4 months ago
627
12
Laravel

Seeding with Carbon dates

Posted 4 months ago by xtremer360

I'm trying to figure out how to fix the following code. When this code runs, it will succerssfully create rows up until a point when the ended at date will start being before the started date and I'm not exactly sure what I'm doing wrong.

Anyone have enough experience with Carbon dates and be able to see my issue?

$dateToStart = Carbon::now()->subYears(5);

$diffInYears = $dateToStart->diffInYears(now());
$minYears = ceil($diffInYears*.25);
$maxYears = floor($diffInYears*.75);
$randomNumberOfYearsEmployed = rand($minYears, $maxYears);

for ($i = 1; $i <= 12*$diffInYears; $i++) {
    for ($j = 1; $j <= 5; $j++) {
        PlayerFactory::new()
            ->released(
                EmploymentFactory::new()
                    ->started(
                        $dateToStart->copy()->addMonth($i)
                    )
                    ->ended(
                        now()->subYears($randomNumberOfYearsEmployed)->subMonths(rand(1, 11))
                    )
            )
            ->create(['name' => 'Player '.$eNum]);

        $eNum ++;
    }
}

Please sign in or create an account to participate in this conversation.