Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 67 ยท Databases and Migrations

Seeders and Factories

Fill your Laravel database with data: write seeders, define model factories with fake data, use states and sequences, and build related records with has() and for().

An empty database makes a poor development environment. You cannot judge a page of search results with two rows, and you cannot test a report without data. Laravel gives you two tools for this. A seeder is a class that puts data into the database. A factory is a recipe for building one realistic model, with fake names, emails and dates, that you can stamp out once or a thousand times.

The same factories pay off again in your tests (HTTP and database tests): instead of hand-writing every attribute of a user, you ask for User::factory()->create() and override only what the test cares about. This lesson shows how to write seeders and factories, how states and sequences vary the data, and how related records are built. It follows migrations, which create the tables these tools fill.

Seeders

Generate one with Artisan:

Terminal
php artisan make:seeder RoleSeeder

A seeder has one method, run():

PHP
namespace Database\Seeders;

use App\Models\Role;
use Illuminate\Database\Seeder;

class RoleSeeder extends Seeder
{
    public function run(): void
    {
        foreach (['admin', 'editor', 'reader'] as $name) {
            Role::firstOrCreate(['name' => $name]);
        }
    }
}

firstOrCreate makes the seeder safe to run twice: it creates the role only when it is missing. That matters for reference data such as roles, countries or plans, which real production databases need. Fake data, on the other hand, belongs in development and testing only.

database/seeders/DatabaseSeeder.php is the entry point. It calls the others in order, so a table that other tables depend on is filled first:

PHP
class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $this->call([
            RoleSeeder::class,
            UserSeeder::class,
            PostSeeder::class,
        ]);
    }
}

Run it with these commands:

Terminal
php artisan db:seed                       # run DatabaseSeeder
php artisan db:seed --class=RoleSeeder    # run one seeder
php artisan migrate:fresh --seed          # rebuild the schema, then seed
php artisan db:seed --force               # needed in production

Writing a factory

A factory lives in database/factories and has a definition() method returning the default attributes of one model:

Terminal
php artisan make:factory PostFactory
PHP
namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

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_at' => fake()->dateTimeBetween('-1 year', 'now'),
        ];
    }
}

fake() returns a Faker generator: name(), safeEmail(), sentence(), paragraph(), numberBetween(), randomElement([...]), dateTimeBetween(), boolean() and many more. unique() guarantees no repeats within one run, which matters for columns with a unique index.

The model connects to its factory through the HasFactory trait, so Post::factory() works (the naming convention Database\Factories\PostFactory is found automatically). Then you choose what to do with it:

PHP
$one  = Post::factory()->make();             // a model in memory, not saved
$post = Post::factory()->create();           // saved to the database
$many = Post::factory()->count(20)->create();
$post = Post::factory()->create(['title' => 'Hello']); // override attributes

make() is perfect for unit tests that never touch the database; create() saves the record (the model methods are explained in Eloquent basics).

Faker output is random each run, which is fine for development but awkward when you want a screenshot to match. Call fake()->seed(1234) at the top of a seeder to make the sequence repeatable.

States and sequences

A state is a named variation of the default. You write it as a method on the factory and chain it when needed:

PHP
public function draft(): static
{
    return $this->state(fn (array $attributes) => [
        'published_at' => null,
    ]);
}

public function popular(): static
{
    return $this->state(['views' => 10_000]);
}
PHP
Post::factory()->draft()->count(5)->create();
Post::factory()->popular()->draft()->create();   // states combine

A sequence cycles through values, which is how you create varied but controlled data:

PHP
use Illuminate\Database\Eloquent\Factories\Sequence;

User::factory()
    ->count(6)
    ->state(new Sequence(
        ['role' => 'admin'],
        ['role' => 'editor'],
        ['role' => 'reader'],
    ))
    ->create();   // admin, editor, reader, admin, editor, reader

A shorter form, ->sequence(['role' => 'admin'], ['role' => 'reader']), does the same for arrays of attributes.

The first stand-in mimics this API: an immutable factory with state(), sequence(), count() and make(). It uses a seeded number generator so the "fake" data is identical on every run, which is also the idea behind fake()->seed().

PHP A factory with states and sequences

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each call returns a new factory (clone), which is how Laravel's factories behave too: $base = User::factory(); can be reused with different states without one use leaking into the next.

Relationships in factories

Related records can be created three ways.

Inside the definition. Using another factory as an attribute value, like 'user_id' => User::factory() above, creates a parent for each child and fills in its ID.

From the parent, with has. Build a user together with its posts:

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

User::factory()->hasPosts(3)->create();   // magic shortcut, same result

The relationship name comes from the model (see Eloquent relationships); hasPosts is translated into has(Post::factory(), 'posts').

From the child, with for. Attach children to a parent you already have, or let one be made:

PHP
Post::factory()->count(3)->for($user)->create();
Post::factory()->count(3)->for(User::factory()->state(['name' => 'Ada']))->create();

For many-to-many relations there is hasAttached(Role::factory()->count(2), ['assigned_by' => 1]), which also fills pivot columns. And when many models should share one parent instead of each creating its own, Post::factory()->count(10)->recycle($users)->create() picks parents from an existing collection.

The final piece of a good dev setup is a seeder that combines everything:

PHP
class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $this->call(RoleSeeder::class);

        User::factory()->create([
            'name' => 'Test User',
            'email' => '[email protected]',
        ]);

        User::factory()->count(10)->hasPosts(5)->create();
    }
}
flowchart TD
    A["db:seed"] --> B["DatabaseSeeder::run()"]
    B --> C["RoleSeeder<br/>reference data"]
    B --> D["User::factory()<br/>10 users"]
    D --> E["hasPosts(5)<br/>50 posts"]
    E --> F[("database")]
    C --> F
    D --> F

The seeder calls factories; each factory creates parents first and then their children.

The second stand-in saves to a real SQLite database and supports has(), so you can watch the parent-first, child-second order and the foreign keys line up.

PHP A factory with create() and has() on SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Using factories well

  • Keep definition() valid and minimal: the cheapest model that satisfies every constraint. Put special cases in states (admin(), suspended(), draft()) with names that read like sentences.
  • Do not seed fake data in production. Reference data goes in idempotent seeders (firstOrCreate, upsert); migrate:fresh --seed is a development command.
  • Avoid creating more than you need. Each create() is a database write, so in tests prefer make() for pure logic and create() only for rows a query must find.
  • Seed passwords with a fixed, known value (a factory typically hashes 'password' once and reuses it), so you can sign in as any seeded user while developing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between Post::factory()->make() and Post::factory()->create()?

    make() returns an unsaved model, which is ideal for tests that do not need the database. create() inserts the row as well.
  2. 2. Which line builds three users who alternate between the admin and reader roles?

    sequence() cycles through the given attribute sets, so three users get admin, reader, admin.
  3. 3. A seeder creates the default roles. How should it be written so running it twice is harmless?

    firstOrCreate only inserts the role if it does not exist, which makes the seeder idempotent and safe for reference data.
  4. 4. What does User::factory()->count(10)->hasPosts(5)->create() do?

    has... applies to every user created, so each of the ten users gets five posts.

Summary

  • Seeders (make:seeder, db:seed, migrate:fresh --seed) fill the database; DatabaseSeeder calls the others in dependency order.
  • Make seeders for reference data idempotent with firstOrCreate; keep fake data to development and tests.
  • A factory's definition() returns default attributes using fake(); make() builds in memory, create() saves, and count() repeats.
  • States (state() and named methods) vary the defaults and combine; sequence() cycles through values.
  • Relationships: use another factory as an attribute, has() / hasPosts(3) from the parent, for($user) from the child, hasAttached() for many-to-many and recycle() to share parents.
  • Factories return new instances, so a base factory can be reused safely.

Next: Eloquent Models and CRUD