Laravel Seeding: date manipulation not working

138 views Asked by At

I have a pivot table that I want to seed. Besides the PK and the FK, the table also contains two more columns: Arrival & Departure (type: timestamps). I'm using Carbon to populate randomly the preceding columns. Here's my code:

$faker = Faker::create();
for( $i=0 ; $i<55500 ; $i++){
   $nowDt = Carbon::now();
   $nowDt->timezone = 'Europe/London';
   $nowDt->addMinutes($faker->numberBetween(25,55));
   $this->command->info("ARRIVAL : ". $nowDt);
   $departure = $nowDt->addMinutes($faker->numberBetween(35,45));
   $this->command->info("DEPARTURE : ". $departure);
   $region->entities()->attach($random_entity,[
            'arrival'       => $nowDt,
            'departure'     => $departure,
            'created_at'    => Carbon::now(),
            'updated_at'    => Carbon::now()
        ]);
   }

The weird thing is, the messages outputted to the console are the following:

ARRIVAL : 2015-06-11 08:24:29
DEPARTURE : 2015-06-11 09:13:29

But when I look at the data inserted, arrival and departure have the exact same value.

ARRIVAL : 2015-06-11 08:24:29
DEPARTURE : 2015-06-11 08:24:29

What am I doing wrong here ?

1

There are 1 answers

0
chanafdo On BEST ANSWER

It's because you are manipulating the same date object. If you need to manipulate a date and return as a new object preserving the current object use copy method before manipulating. Else it will return a reference to the same object you are manipulating.

Change this line

$nowDt->addMinutes($faker->numberBetween(35,45));

to

$nowDt->copy()->addMinutes($faker->numberBetween(35,45));