Laravel Seeders and Factories

Laravel Seeders and Factories

Seeders populate your database with test data. Factories define how to generate fake model instances for testing and seeding.

1 - Creating a Factory

php artisan make:factory PostFactory --model=Post
// database/factories/PostFactory.php
class PostFactory extends Factory
{
    public function definition(): array
    {
        return [
            'user_id'      => User::factory(),
            'title'        => fake()->sentence(),
            'slug'         => fake()->unique()->slug(),
            'body'         => fake()->paragraphs(3, true),
            'published'    => fake()->boolean(70),
            'published_at' => fake()->dateTimeThisYear(),
        ];
    }

    // Custom state
    public function draft(): static
    {
        return $this->state(['published' => false, 'published_at' => null]);
    }
}

2 - Creating a Seeder

php artisan make:seeder PostSeeder
class PostSeeder extends Seeder
{
    public function run(): void
    {
        Post::factory(50)->create();
        Post::factory(10)->draft()->create();
    }
}

3 - Running Seeders

php artisan db:seed                       // Run DatabaseSeeder
php artisan db:seed --class=PostSeeder    // Run specific seeder
php artisan migrate:fresh --seed          // Migrate and seed

4 - Using Factories in Tests

// Creates and persists to DB
$user = User::factory()->create();
$posts = Post::factory(3)->for($user)->create();

// Creates without persisting
$post = Post::factory()->make();