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:
// database/seeders/seeders.go
package seeders
import (
"context"
laravel "go.laravel.com"
"app/database/factories"
"app/models"
)
var All = []laravel.Seeder{
{Name: "users", Run: users},
}
func users(ctx context.Context) error {
_, err := factories.User.Create(ctx, func(user *models.User) {
user.Name = "Test User"
user.Email = "test@example.com"
})
return err
}To populate your database with every seeder in the list, run the db:seed command:
laravel db:seedWriting 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:
// database/seeders/roles.go
package seeders
import (
"context"
"go.laravel.com/db"
)
func roles(ctx context.Context) error {
_, err := db.Table("roles").InsertOrIgnore(ctx,
db.Values{"name": "admin"},
db.Values{"name": "editor"},
db.Values{"name": "viewer"},
)
return err
}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:
disk := 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:
// database/seeders/seeders.go
var All = []laravel.Seeder{
{Name: "users", Run: users},
{Name: "roles", Run: roles},
{Name: "posts", Run: posts},
}New applications pass the list to Laravel in bootstrap/app.go:
// bootstrap/app.go
return laravel.Options{
// ...
Migrations: migrations.All,
Seeders: seeders.All,
}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:
// database/seeders/posts.go
package seeders
import (
"context"
"app/database/factories"
)
func posts(ctx context.Context) error {
published := factories.Post.State(factories.Published)
_, err := factories.User.Has("posts", 5, published).CreateMany(ctx, 10)
return err
}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:
// database/seeders/comments.go
package seeders
import (
"context"
laravel "go.laravel.com"
"go.laravel.com/model"
"app/database/factories"
"app/models"
)
func comments(ctx context.Context) error {
if err := laravel.CallSeeder(ctx, "posts"); err != nil {
return err
}
users, err := model.Query[models.User]().Get(ctx)
if err != nil {
return err
}
posts, err := model.Query[models.Post]().Get(ctx)
if err != nil {
return err
}
return factories.Comment.Recycle(users, posts).InsertMany(ctx, 300)
}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):
// database/seeders/users.go
package seeders
import (
"context"
"go.laravel.com/event"
"app/database/factories"
)
func users(ctx context.Context) error {
_, err := factories.User.CreateMany(event.Muted(ctx), 50)
return err
}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:
password, err := hash.Make(ctx, "password")
if err != nil {
return err
}
_, _, err = model.FirstOrCreate[models.User](ctx,
db.Values{"email": "test@example.com"},
db.Values{"name": "Test User", "password": password},
)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:
laravel db:seed
laravel db:seed postsdb:seed prints each seeder as it finishes, with how long it took. A seeder that calls another finishes after the seeder it calls:
◆ roles 2.1ms
◆ posts 118.0ms
◆ comments 41.6ms
◆ 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:
laravel migrate:fresh --seed
laravel migrate:fresh --seeder postsChoosing 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:
laravel db:seed --database reportingForcing 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:
./app db:seed roles --forceSeeding 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.