#Model factory with start and end date gives same date

7 messages · Page 1 of 1 (latest)

covert holly
#

I have a factory defined as so:

    public function definition(): array
    {
        // random date between 1 month ago and 2 weeks in future
        $start = Carbon::now()->addDays(rand(0, 14))->subDays(rand(0, 30));

        // end date between 1 and 7 days after start date
        $end = $start->addDays(rand(1, 7));

        return [
            'name' => fake()->unique()->catchPhrase(),
            'description' => fake()->optional()->sentence(),
            'start' => $start,
            'end' => $end,
            'user_id' => User::factory(),
        ];
    }

For the life of me I can't get the end date to be a different date in the database. When I seed this, it gives me two identical dates.

What am I doing wrong?

limpid halo
#

If I remember correctly, date manipulation functions in Carbon modify the object too.

#

So $start->addDays(rand(1, 7)) will modify $start but also return the new value to $end. So, $start is now equal to $end.

covert holly
#

I thought Carbon was immutable? Maybe I'm wrong?

limpid halo
covert holly
#

Ah, thanks I got it fixed. Had to use Carbon\CarbonImmutable