Search code examples
laraveleachfactoryseedingfaker

Laravel Model seeding in factory with column related to column on same table


I'm seeding some fake data in laravel I have table

Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('parent_id')->default(0);
        $table->string('name');
        $table->integer('depth');
        $table->timestamps();
 });

parent_id must contain data of categories.id

I am wondering is this best way to do it?

CategoriesTableSeeder

factory(App\Category::class, 10)->make()->each(
        function ($c) {
            $c->fill(
                [
                    'parent_id' => App\Category::count() ? App\Category::pluck('id')->random() : 0
                ]
            )->save();
        }
);

CategoryFactory

$factory->define(Category::class, function (Faker $faker) {
    return [
        //'parent_id' => Category::pluck('id')->random(),
        'name' => ucfirst($faker->word),
        'depth' => 0,
    ];
});

Maybe someone can write better solution for same result? I tried a lot, this one works, but i think code should look more professional than now.


Solution

  • 2019_05_03_******_create_categories_table.php

    Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedInteger('parent_id')->default(0);
        $table->string('name')->nullable();
        $table->integer('depth')->default(0);
        $table->timestamps();
    });
    

    CategoryFactory.php

    $factory->define(Category::class, function (Faker $faker) {
        return [
            'parent_id' => Category::count() ? Category::pluck('id')->random() : 0,
            'name' => ucfirst($faker->word),
        ];
    });
    

    CategoriesTableSeeder.php

    public function run()
    {
        factory(Category::class, rand(1, 10))->create()->each(
            function ($category) {
                factory(Category::class, rand(1, 5))->create(['parent_id' => $category->id]);
            }
        );
    }