All Testing lessons

Factories & seeders

5 min read

A model factory is the canonical way to build a model with realistic data.

// database/factories/PostFactory.php
public function definition(): array
{
    return [
        'user_id'      => User::factory(),
        'title'        => fake()->sentence(),
        'body'         => fake()->paragraphs(3, true),
        'is_published' => true,
    ];
}

// State methods for variants
public function draft(): static
{
    return $this->state(fn () => ['is_published' => false]);
}

In tests:

Post::factory()->count(10)->create();
Post::factory()->draft()->for($user)->create();

The for() helper assigns relationships. Combine with has():

User::factory()->has(Post::factory()->count(5))->create();

Seeders

Seeders fill realistic data for local dev. Run with php artisan db:seed.

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        User::factory()->admin()->create(['email' => 'admin@test.local']);
        Post::factory()->count(50)->create();
    }
}

Seeders are also great for environment-specific data (e.g. an initial admin account in production).