DEV Community

Mimis K
Mimis K

Posted on

Laravel Factories & Seeders Structure

Let's start with the case where the model doesn't exist yet.

We need to run the following command:

php artisan make:model Product -mfs
Enter fullscreen mode Exit fullscreen mode

We just created the following files:

  1. Product Model,
  2. Migration file (-m),
  3. ProductFactory (-f)
  4. ProductSeeder (-s)

In case the Product Model exists and we want to create only the ProductFactory, we need the following command:

php artisan make:factory ProductFactory --model=Product

We define the columns we want the products table to have, in the migration file.

    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('description');
            $table->timestamps();
        });
    }
Enter fullscreen mode Exit fullscreen mode

We prepare the ProductFactory with the fields we defined in the migration file. For more options about Factories

    public function definition(): array
    {
        return [
            'name' => fake()->word(),
            'description' => fake()->paragraph(),
        ];
    }
Enter fullscreen mode Exit fullscreen mode

In the ProductSeeder file, we can use the ProductFactory like the example below: For more options about Seeders

    public function run(): void
    {
        Product::factory(20)->create();
    }
Enter fullscreen mode Exit fullscreen mode

In case the Product Model exists and we want to create only the ProductSeeder, we need the following command:

php artisan make:factory ProductSeeder

All seeder files are declared in the database\seeders\DatabaseSeeder.php file.

public function run(): void
{
    $this->call([
        UserSeeder::class,
        ProductSeeder::class
        // more seeders....
    ]);
}
Enter fullscreen mode Exit fullscreen mode

Finally with the following command, we can fill the database with the fake data.

php artisan db:seed
Enter fullscreen mode Exit fullscreen mode

Top comments (0)