phplaravellaravel-5.4laravel-seeding

Laravel Factory: Manual Increment of Column


For the following factory definition, the column order needs to be sequential. There is already a column id that is auto-incremented. The first row's order should start at 1 and each additional row's order should be the next number (1,2,3, etc.)

$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
    return [
        'user_id' => App\User::inRandomOrder()->first()->id,
        'command' => $faker->word,
        'content' => $faker->sentence,
        'order'   => (App\AliasCommand::count()) ?
            App\AliasCommand::orderBy('order', 'desc')->first()->order + 1 : 1
    ];
});

It should be setting the order column to be 1 more than the previous row, however, it results in all rows being assigned 1.


Solution

  • Here's something that might work.

    $factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
        static $order = 1;   
        return [
            'user_id' => App\User::inRandomOrder()->first()->id,
            'command' => $faker->word,
            'content' => $faker->sentence,
            'order'   => $order++
        ];
    });
    

    It just keeps a counter internal to that function.

    Update:

    Laravel 8 introduced new factory classes so this request becomes:

    class AliasCommandFactory extends Factory {
    
        private static $order = 1;
    
        protected $model = AliasCommand::class;
    
        public function definition() {
             $faker = $this->faker;
             return [
                'user_id' => User::inRandomOrder()->first()->id,
                'command' => $faker->word,
                'content' => $faker->sentence,
                'order'   => self::$order++
            ];
        }
    }