Jeffrey Davidson
Jeffrey Davidson

Reputation: 151

Looping Over Creation of Models

What I'm attempting to do is create 5 new models for each month of the year.

for ($i = 1; $i <= 12; $i++) {
    for ($j = 51; $j <= 55; $j++) {
        factory(Employee::class)->create([
            'name' => 'Employee '. $j,
        ])->employments()->create(['started_at' => now()->subYear(1)->addMonth($i);
    }
}

Currently, the problem is that after each month it starts the count back at 51. I'd like it for it to continue on from the last number it was on.

Upvotes: 1

Views: 29

Answers (1)

Watercayman
Watercayman

Reputation: 8178

Take the printable employee number (previously $j) out of the loop so that it won't reset as per the instructions of the for loop itself:

$eNum = 1;
for ($i = 1; $i <= 12; $i++) {
   for ($j = 51; $j <= 55; $j++) {
       factory(Employee::class)->create([
           'name' => 'Employee '. $eNum,
       ])->employments()->create(['started_at' => now()->subYear(1)->addMonth($i);
       $eNum ++;
   }
}

The $j variable doesn't really matter in terms of printing now - and can start at 1 or 51 or whatever you like. If you are looking to print the number and continue to increment, just keep the printable var ($eNum) outside the loop.

Upvotes: 1

Related Questions