agyanadda@gmail.com

Laravel Seeders and Factories

Database and Eloquent 1 min read Updated Dec 2, 2026 Topic 15 of 31

While building an app you need data to look at. Factories create fake model data, and seeders run them to fill the database.

Factories

php artisan make:factory PostFactory creates database/factories/PostFactory.php. In its definition() method, return fake values using fake():

  • fake()->sentence(), fake()->paragraphs(3, true)
  • fake()->name(), fake()->unique()->safeEmail()
  • fake()->numberBetween(1, 100), fake()->boolean()

The model needs the HasFactory trait (the default User model already has it).

Using factories

  • Post::factory()->create() — one post saved
  • Post::factory(20)->create() — twenty posts
  • Post::factory()->make() — build without saving
  • User::factory(5)->has(Post::factory(3))->create() — 5 users with 3 posts each

Seeders

database/seeders/DatabaseSeeder.php is the main seeder. Create more with php artisan make:seeder CategorySeeder and call them from DatabaseSeeder.

Commands

  • php artisan db:seed — run DatabaseSeeder
  • php artisan migrate:fresh --seed — rebuild every table and seed (deletes data, development only)

Example

Example — Factory and seeder PHP
<?php
// database/factories/PostFactory.php
public function definition(): array
{
    return [
        'user_id'      => \App\Models\User::factory(),
        'title'        => fake()->sentence(6),
        'body'         => fake()->paragraphs(3, true),
        'is_published' => fake()->boolean(80),
    ];
}

// database/seeders/DatabaseSeeder.php
public function run(): void
{
    \App\Models\User::factory()->create([
        'name'  => 'Admin',
        'email' => 'admin@example.com',
    ]);

    \App\Models\User::factory(5)
        ->has(\App\Models\Post::factory(3))
        ->create();
}

php artisan db:seed creates 1 admin and 5 users with 3 posts each — 15 posts with random titles, about 80% of them published.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which command rebuilds all tables and runs the seeders?

Exercise 2 True / False

Post::factory()->make() saves the post to the database.

Exercise 3 Fill in the Blank

Inside a factory, fake values come from the ___() helper.

Frequently Asked Questions

Use seeders on production only for required starting data, such as categories, roles or settings, and make sure they do not create duplicates (for example, use firstOrCreate). Never run fake-data factories or migrate:fresh on a live database.