Skip to content

Seeding

Database

Database: Seeding

Introduction

Laravel includes the ability to seed your database with test data using seeders, giving you a test account, sample records, and baseline reference data right after running migrations.

A seeder is a named function that writes rows. New applications list their seeders in database/seeders/seeders.go, and db:seed runs every seeder in the list, in order. For example, this seeder creates a test user with the User factory that new applications include:

1// database/seeders/seeders.go
2package seeders
3 
4import (
5 "context"
6 
7 laravel "go.laravel.com"
8 
9 "app/database/factories"
10 "app/models"
11)
12 
13var All = []laravel.Seeder{
14 {Name: "users", Run: users},
15}
16 
17func users(ctx context.Context) error {
18 _, err := factories.User.Create(ctx, func(user *models.User) {
19 user.Name = "Test User"
20 user.Email = "[email protected]"
21 })
22 
23 return err
24}
1// database/seeders/seeders.go
2package seeders
3 
4import (
5 "context"
6 
7 laravel "go.laravel.com"
8 
9 "app/database/factories"
10 "app/models"
11)
12 
13var All = []laravel.Seeder{
14 {Name: "users", Run: users},
15}
16 
17func users(ctx context.Context) error {
18 _, err := factories.User.Create(ctx, func(user *models.User) {
19 user.Name = "Test User"
20 user.Email = "[email protected]"
21 })
22 
23 return err
24}

To populate your database with every seeder in the list, run the db:seed command:

1laravel db:seed
1laravel db:seed

Writing seeders

A seeder's Run function takes a context and returns an error. The context carries the seeding run's transaction, so every row you write with that ctx commits or rolls back with the rest of the run. Inside a seeder, you may write rows with models, the query builder, raw SQL, or model factories. The seeder's Name is the name you pass to db:seed to run it alone. For example, this seeder creates your application's default roles:

1// database/seeders/roles.go
2package seeders
3 
4import (
5 "context"
6 
7 "go.laravel.com/db"
8)
9 
10func roles(ctx context.Context) error {
11 _, err := db.Table("roles").InsertOrIgnore(ctx,
12 db.Values{"name": "admin"},
13 db.Values{"name": "editor"},
14 db.Values{"name": "viewer"},
15 )
16 
17 return err
18}
1// database/seeders/roles.go
2package seeders
3 
4import (
5 "context"
6 
7 "go.laravel.com/db"
8)
9 
10func roles(ctx context.Context) error {
11 _, err := db.Table("roles").InsertOrIgnore(ctx,
12 db.Values{"name": "admin"},
13 db.Values{"name": "editor"},
14 db.Values{"name": "viewer"},
15 )
16 
17 return err
18}

Because InsertOrIgnore skips a row that already exists (assuming a unique index on name), running this seeder again won't insert duplicate roles.

A seeder's ctx reaches the rest of your application, as a console command's does, so you may call config.From(ctx), storage.From(ctx), and your models in a seeder:

1disk := storage.From(ctx)
1disk := storage.From(ctx)

Where seeders live

New applications give each seeder a file of its own in database/seeders, and list them in All in database/seeders/seeders.go. Adding a seeder takes two steps: write its function, and add it to All. db:seed runs the seeders in the order of the list, so put a seeder after the seeders whose rows it needs:

1// database/seeders/seeders.go
2var All = []laravel.Seeder{
3 {Name: "users", Run: users},
4 {Name: "roles", Run: roles},
5 {Name: "posts", Run: posts},
6}
1// database/seeders/seeders.go
2var All = []laravel.Seeder{
3 {Name: "users", Run: users},
4 {Name: "roles", Run: roles},
5 {Name: "posts", Run: posts},
6}

New applications pass the list to Laravel in bootstrap/app.go:

1// bootstrap/app.go
2return laravel.Options{
3 // ...
4 Migrations: migrations.All,
5 Seeders: seeders.All,
6}
1// bootstrap/app.go
2return laravel.Options{
3 // ...
4 Migrations: migrations.All,
5 Seeders: seeders.All,
6}

An installed package may add seeders of its own, such as a billing package's plans. db:seed runs the package's seeders before yours, so your seeders may use their rows.

Using model factories

Writing out columns for dozens of records by hand quickly becomes tedious. You may use model factories inside seeders to generate realistic test data. For example, this seeder uses the User factory and a Post factory like the one in the factories guide to create ten users with five published posts each:

1// database/seeders/posts.go
2package seeders
3 
4import (
5 "context"
6 
7 "app/database/factories"
8)
9 
10func posts(ctx context.Context) error {
11 published := factories.Post.State(factories.Published)
12 
13 _, err := factories.User.Has("posts", 5, published).CreateMany(ctx, 10)
14 
15 return err
16}
1// database/seeders/posts.go
2package seeders
3 
4import (
5 "context"
6 
7 "app/database/factories"
8)
9 
10func posts(ctx context.Context) error {
11 published := factories.Post.State(factories.Published)
12 
13 _, err := factories.User.Has("posts", 5, published).CreateMany(ctx, 10)
14 
15 return err
16}

When seeding thousands of rows that you don't need back as models, call InsertMany on the factory instead of CreateMany, which writes many rows in each statement rather than one insert per model.

Calling other seeders

When a seeder needs rows that another seeder writes, you may run the other seeder first. Call laravel.CallSeeder with the ctx your seeder received and the other seeder's name. The other seeder's rows join the run's transaction.

Each seeder runs at most once per db:seed run, even when All lists it and other seeders call it too. That means a seeder can safely call the seeders it depends on without creating duplicate records. For example, comments calls the posts seeder, so running db:seed comments on its own still has posts to comment on. It then uses a Comment factory like the one in the factories guide's section on recycling models to spread three hundred comments over the existing users and posts:

1// database/seeders/comments.go
2package seeders
3 
4import (
5 "context"
6 
7 laravel "go.laravel.com"
8 "go.laravel.com/model"
9 
10 "app/database/factories"
11 "app/models"
12)
13 
14func comments(ctx context.Context) error {
15 if err := laravel.CallSeeder(ctx, "posts"); err != nil {
16 return err
17 }
18 
19 users, err := model.Query[models.User]().Get(ctx)
20 if err != nil {
21 return err
22 }
23 
24 posts, err := model.Query[models.Post]().Get(ctx)
25 if err != nil {
26 return err
27 }
28 
29 return factories.Comment.Recycle(users, posts).InsertMany(ctx, 300)
30}
1// database/seeders/comments.go
2package seeders
3 
4import (
5 "context"
6 
7 laravel "go.laravel.com"
8 "go.laravel.com/model"
9 
10 "app/database/factories"
11 "app/models"
12)
13 
14func comments(ctx context.Context) error {
15 if err := laravel.CallSeeder(ctx, "posts"); err != nil {
16 return err
17 }
18 
19 users, err := model.Query[models.User]().Get(ctx)
20 if err != nil {
21 return err
22 }
23 
24 posts, err := model.Query[models.Post]().Get(ctx)
25 if err != nil {
26 return err
27 }
28 
29 return factories.Comment.Recycle(users, posts).InsertMany(ctx, 300)
30}

If you need a reusable helper that runs more than once with different arguments, such as creating two teams of different sizes, write a plain function that takes ctx and those values instead of a seeder, and call it from your seeders. Its writes join the run's transaction too.

Muting model events

When seeding development data, you typically don't want model events firing side effects such as welcome emails. Set WithoutEvents: true on a seeder in database/seeders/seeders.go to mute model events for the whole seeder, or wrap individual writes with event.Muted(ctx):

1// database/seeders/users.go
2package seeders
3 
4import (
5 "context"
6 
7 "go.laravel.com/event"
8 
9 "app/database/factories"
10)
11 
12func users(ctx context.Context) error {
13 _, err := factories.User.CreateMany(event.Muted(ctx), 50)
14 
15 return err
16}
1// database/seeders/users.go
2package seeders
3 
4import (
5 "context"
6 
7 "go.laravel.com/event"
8 
9 "app/database/factories"
10)
11 
12func users(ctx context.Context) error {
13 _, err := factories.User.CreateMany(event.Muted(ctx), 50)
14 
15 return err
16}

Model hooks still run, so fields set in a Creating hook (such as slugs) are still set. To mute the seeders that a seeder calls as well, pass event.Muted(ctx) to laravel.CallSeeder.

Seeders you can run again

Running the users seeder from the introduction twice fails on the email column's unique index, because the test user already exists. During local development, migrate:fresh --seed avoids this by starting from an empty database. For a seeder you intend to run in production, such as one that adds default roles, make it safe to run again with model.FirstOrCreate, model.UpdateOrCreate, model.Upsert, or InsertOrIgnore (as in the roles seeder above).

For example, this version of the users seeder looks up the test user by email address, and creates the user from both sets of values only when no row matches:

1password, err := hash.Make(ctx, "password")
2if err != nil {
3 return err
4}
5 
6_, _, err = model.FirstOrCreate[models.User](ctx,
7 db.Values{"email": "[email protected]"},
8 db.Values{"name": "Test User", "password": password},
9)
1password, err := hash.Make(ctx, "password")
2if err != nil {
3 return err
4}
5 
6_, _, err = model.FirstOrCreate[models.User](ctx,
7 db.Values{"email": "[email protected]"},
8 db.Values{"name": "Test User", "password": password},
9)

Rows that your application needs before it can handle requests belong in a migration instead, so they're written once on every database, as part of every deployment.

Running seeders

Run db:seed to run every seeder in All, or pass a seeder's name to run only that seeder:

1laravel db:seed
2laravel db:seed posts
1laravel db:seed
2laravel db:seed posts

db:seed prints each seeder as it finishes, with how long it took. A seeder that calls another finishes after the seeder it calls:

1◆ roles 2.1ms
2◆ posts 118.0ms
3◆ comments 41.6ms
4◆ Database seeded.
1◆ roles 2.1ms
2◆ posts 118.0ms
3◆ comments 41.6ms
4◆ Database seeded.

Laravel wraps each db:seed run in a single transaction, so if any seeder fails, Laravel rolls back everything the run wrote. On MySQL and MariaDB, statements that change a table, such as TRUNCATE or CREATE TABLE, commit the transaction early, so the rows written before them are kept.

If foreign key constraints make the order of your inserts difficult, wrap the writes in schema.WithoutForeignKeyConstraints. On PostgreSQL, this applies only to foreign keys created with .Deferrable().

Seeding after migrating

To rebuild and seed your development database in one command, pass --seed to migrate:fresh, or pass --seeder with a seeder's name to run only that seeder. The migrate command accepts the same options:

1laravel migrate:fresh --seed
2laravel migrate:fresh --seeder posts
1laravel migrate:fresh --seed
2laravel migrate:fresh --seeder posts

Choosing a connection

Seeders write to your default database unless you name another connection with --database. While the command runs, the seeders' ctx carries a transaction on that connection, so your models and queries write to it:

1laravel db:seed --database reporting
1laravel db:seed --database reporting

Forcing seeders to run in production

Because seeding can change or replace data, db:seed asks for confirmation in production. Pass --force to run without the prompt, such as in a deployment script. On a server, run your compiled binary instead of laravel:

1./app db:seed roles --force
1./app db:seed roles --force

Seeding in tests

To run seeders inside your test suite (for a single test, or once for each copy of the test database), check out the testing guide's section on seeding the database.