Database: Model Factories
- Introduction
- Defining factories
- Creating models with factories
- Factory relationships
- After creating callbacks
- Inserting many rows
- Fake data
- Testing with factories
Introduction
When you test your application or seed your database, you often need realistic rows to work with, such as a user and a post for an authorization test or fifty users for a local demo. Writing out every column in every test adds boilerplate, and when you add a required column, every one of those tests breaks.
Model factories give each model a sensible default for each column, so your tests and seeders only set the columns they care about. In a test, you create models through the test client:
1user := client.Create(factories.User)2posts := client.CreateMany(3, factories.Post.For("user", user))1user := client.Create(factories.User)2posts := client.CreateMany(3, factories.Post.For("user", user))
New applications include a factory for the User model in database/factories/user.go:
1// database/factories/user.go2package factories34import (5 "go.laravel.com/factory"67 "app/models"8)910// User makes a verified user whose password is "password".11var User = factory.New(func(fake *factory.Faker) models.User {12 return models.User{13 Name: fake.Name(),14 Email: fake.Unique().Email(),15 EmailVerifiedAt: new(fake.Now()),16 Password: fake.Password(),17 }18})1920// Unverified makes the user's email address unverified.21func Unverified(_ *factory.Faker, user *models.User) {22 user.EmailVerifiedAt = nil23}1// database/factories/user.go2package factories34import (5 "go.laravel.com/factory"67 "app/models"8)910// User makes a verified user whose password is "password".11var User = factory.New(func(fake *factory.Faker) models.User {12 return models.User{13 Name: fake.Name(),14 Email: fake.Unique().Email(),15 EmailVerifiedAt: new(fake.Now()),16 Password: fake.Password(),17 }18})1920// Unverified makes the user's email address unverified.21func Unverified(_ *factory.Faker, user *models.User) {22 user.EmailVerifiedAt = nil23}
factory.New takes the factory's definition, a function that receives a *factory.Faker for generating fake data and returns the model with its default values. It returns a *factory.Factory[models.User], which you keep in a package variable. Unverified is a reusable state, a plain function that changes a model the factory built. You don't register factories or states anywhere.
Factories insert their models with model.Create, so hooks, events, timestamps, and database defaults behave as they do in a handler. Each Create or CreateMany call runs in a single transaction, so a model, its parents, and its children commit or roll back together.
Defining factories
Where factories live
Keep each model's factory and its states in database/factories, in a file named for the model, such as database/factories/post.go. Every file in the directory belongs to the factories package, so tests and seeders import app/database/factories once and reach each factory by name, such as factories.Post.
A definition sets each column that has no default in the database. Leave out the ID and the timestamps, which the database and model.Create fill in, and any column you've tagged db:",default". When you add a required column to a model, add it to the model's factory too, so the tests that use the factory keep passing.
Parents in a factory
A post belongs to a user, so a post's factory needs a user for each post it creates. For example, here's a factory for a Post model like the one in the model relationships guide, which has a UserID column, a PublishedAt column that may be NULL, and a User field tagged model:"belongs_to". Ending the factory with For("user", User) gives each post a user of its own:
1// database/factories/post.go2package factories34import (5 "go.laravel.com/factory"67 "app/models"8)910// Post makes a draft post, with a user of its own.11var Post = factory.New(func(fake *factory.Faker) models.Post {12 return models.Post{Title: fake.Sentence()}13}).For("user", User)1// database/factories/post.go2package factories34import (5 "go.laravel.com/factory"67 "app/models"8)910// Post makes a draft post, with a user of its own.11var Post = factory.New(func(fake *factory.Faker) models.Post {12 return models.Post{Title: fake.Sentence()}13}).For("user", User)
Before the factory inserts each post, it creates a user with the User factory in the same transaction, sets the post's user_id, and puts the user in the post's User field. Whenever a caller supplies a user itself, through a later For, Has, or a state that sets UserID, Laravel skips the User factory completely.
morph_to relationships also accept a factory, so a comment's factory may end with For("commentable", Post), while a test that calls For("commentable", video) attaches the comment to a video instead.
Factory states
Factory states let you define reusable changes to a model's default values, such as a published post or a user who hasn't verified their email address. Write each state as a function that takes the faker and a pointer to the model and sets the columns it changes:
1// database/factories/post.go2func Published(fake *factory.Faker, post *models.Post) {3 post.PublishedAt = new(fake.Now().AddDate(0, 0, -1))4}56func Scheduled(fake *factory.Faker, post *models.Post) {7 post.PublishedAt = new(fake.Future(7 * 24 * time.Hour))8}1// database/factories/post.go2func Published(fake *factory.Faker, post *models.Post) {3 post.PublishedAt = new(fake.Now().AddDate(0, 0, -1))4}56func Scheduled(fake *factory.Faker, post *models.Post) {7 post.PublishedAt = new(fake.Future(7 * 24 * time.Hour))8}
To apply states, pass them to the factory's State method. States run after the definition in the order you pass them, so when two states set the same column, the later state's value wins:
1post := client.Create(factories.Post.State(factories.Published))1post := client.Create(factories.Post.State(factories.Published))
If a state needs a value from the caller, such as a post's title, write a function that takes the value and returns the state:
1// database/factories/post.go2func Titled(title string) func(*factory.Faker, *models.Post) {3 return func(_ *factory.Faker, post *models.Post) {4 post.Title = title5 }6}1// database/factories/post.go2func Titled(title string) func(*factory.Faker, *models.Post) {3 return func(_ *factory.Faker, post *models.Post) {4 post.Title = title5 }6}
Then pass the returned state to State as you would any other, such as factories.Post.State(factories.Titled("Hello")).
A factory's methods return a new factory and leave the factory you call them on unchanged. If several tests use the same variation, you may call State once and keep the new factory in a variable:
1// database/factories/post.go2var PublishedPost = Post.State(Published)1// database/factories/post.go2var PublishedPost = Post.State(Published)
A state that sets a time should read it from fake.Now(), fake.Past, or fake.Future rather than from time.Now(). The faker counts from your application's clock, so in a test that travels in time, Published still dates the post a day before the test's time.
Creating models with factories
In a test, create models with the test client's Create and CreateMany methods. Create inserts a single model and returns it as the database stored it, with its ID, timestamps, and defaults. CreateMany inserts the number of models you ask for and returns a slice:
1user := client.Create(factories.User)23users := client.CreateMany(3, factories.User.State(factories.Unverified))1user := client.Create(factories.User)23users := client.CreateMany(3, factories.User.State(factories.Unverified))
Both methods insert through the client's database, so with laraveltest.RefreshDatabase, the rows disappear when the test ends. Both also fail the test when an insert fails, so you don't check an error. CreateMany creates all of its models in one transaction, so when one insert fails, none of the models stay.
Using factories in seeders
A seeder has no test client, so it calls the factory's own Create, CreateMany, and InsertMany methods, which take a context.Context and return an error. The methods write through that context, so the rows join the seeder's transaction. For example, this seeder creates ten users with three posts each:
1// database/seeders/users.go2package seeders34import (5 "context"67 "app/database/factories"8)910func users(ctx context.Context) error {11 _, err := factories.User.Has("posts", 3, factories.Post).CreateMany(ctx, 10)1213 return err14}1// database/seeders/users.go2package seeders34import (5 "context"67 "app/database/factories"8)910func users(ctx context.Context) error {11 _, err := factories.User.Has("posts", 3, factories.Post).CreateMany(ctx, 10)1213 return err14}
Every factory in one db:seed run shares the run's faker, so the faker's unique values don't repeat across seeders, and it hashes the password only once.
Factories dispatch model events for every model they create, so a listener might send a welcome email to each seeded user. To seed without events, pass event.Muted(ctx) in place of ctx.
Overriding columns
To set specific columns for one call, such as a user's name that a test checks on their profile page, pass a function literal after the factory. The function receives the model after the factory's states have run, and the compiler checks each field's name and type:
1taylor := client.Create(factories.User, func(u *models.User) {2 u.Name = "Taylor"4})1taylor := client.Create(factories.User, func(u *models.User) {2 u.Name = "Taylor"4})
You may combine overrides with Has to create related models at the same time:
1user := client.Create(factories.User.Has("posts", 3, factories.Post), func(u *models.User) {2 u.Name = "Taylor"3})1user := client.Create(factories.User.Has("posts", 3, factories.Post), func(u *models.User) {2 u.Name = "Taylor"3})
An override passed to CreateMany applies to every model it creates. To give each model a different value, use a sequence instead.
Making models without saving them
Some code takes a model but never reads the database, such as a policy or a function that formats a user's name. For that code, Make builds the model with the definition and states but doesn't insert it, so its ID is zero:
1post := client.Make(factories.Post.State(factories.Published))1post := client.Make(factories.Post.State(factories.Published))
Make creates no parents, so the post above has no user unless you pass For a user that already exists.
Sequences
Use Sequence when a column should vary from one created model to the next. The function receives the faker, each model, and the model's zero-based index in the call. For example, this creates ten users with every second user unverified:
1users := client.CreateMany(10, factories.User.Sequence(func(_ *factory.Faker, user *models.User, i int) {2 if i%2 == 1 {3 user.EmailVerifiedAt = nil4 }5}))1users := client.CreateMany(10, factories.User.Sequence(func(_ *factory.Faker, user *models.User, i int) {2 if i%2 == 1 {3 user.EmailVerifiedAt = nil4 }5}))
Factory relationships
Most tests need related rows, such as a user with a few posts or a post with tags. A factory's relationship methods create those rows along with the model. Each method takes the name of a relationship field in snake case, as model.Load does, such as "user" for User and "posts" for Posts. If the model has no relationship by that name, or the relationship is of the wrong kind, the method panics with a message that names the fix, so the first test that uses the factory finds the mistake.
Has one and has many
Use Has to create related child models for each model through a has_one or has_many relationship. Pass Has the relationship, how many children to create, and their factory:
1user := client.Create(factories.User.Has("posts", 3, factories.Post.State(factories.Published)))23fmt.Println(len(user.Posts)) // 31user := client.Create(factories.User.Has("posts", 3, factories.Post.State(factories.Published)))23fmt.Println(len(user.Posts)) // 3
Laravel sets each child's foreign key to the new parent's ID, so the post factory's own For("user", User) doesn't create another user. The returned models hold the relationships that the factory wrote, so user.Posts holds the three posts and each post's User holds the new user without extra queries. Children created through a morph_one or morph_many relationship get their type column and their morph_to field set too. You may nest Has calls to build multi-level trees:
1users := client.CreateMany(5, factories.User.Has(2 "posts", 3, factories.Post.Has("comments", 2, factories.Comment),3))1users := client.CreateMany(5, factories.User.Has(2 "posts", 3, factories.Post.Has("comments", 2, factories.Comment),3))
This creates 5 users, 15 posts, and 30 comments in one transaction.
Because a has_one relationship holds a single model, such as a user's Profile *Profile field, use HasOne:
1user := client.Create(factories.User.HasOne("profile", factories.Profile))1user := client.Create(factories.User.HasOne("profile", factories.Profile))
Belongs to
Use For to give created models a parent through a belongs_to relationship. For accepts either a model that exists or another factory:
1user := client.Create(factories.User)23posts := client.CreateMany(3, factories.Post.For("user", user))45posts = client.CreateMany(3, factories.Post.For("user", factories.User.State(factories.Unverified)))1user := client.Create(factories.User)23posts := client.CreateMany(3, factories.Post.For("user", user))45posts = client.CreateMany(3, factories.Post.For("user", factories.User.State(factories.Unverified)))
The first call gives all three posts to user. The second call creates an unverified user for each post. In both calls, the For("user", User) in the Post factory doesn't run, because a later For on the same relationship replaces it. To give several models one new parent, create the parent first and pass the model, as the first call does.
For also accepts a morph_to relationship, with a model or a factory of any model that implements the relationship's interface. For sets the type column along with the key:
1video := client.Create(factories.Video)23comments := client.CreateMany(3, factories.Comment.For("commentable", video))45comments = client.CreateMany(3, factories.Comment.For("commentable", factories.Post))1video := client.Create(factories.Video)23comments := client.CreateMany(3, factories.Comment.For("commentable", video))45comments = client.CreateMany(3, factories.Comment.For("commentable", factories.Post))
The first call puts all three comments on video, and the second creates a post for each comment. For panics when you pass it a model whose ID is zero, since a model that doesn't exist yet can't be a parent. Create the model first, or pass its factory.
Belongs to many
Through a belongs_to_many relationship, Has creates new related models and links each one with a join row. To link models that already exist, pass the models (or their keys) to Attach:
1post := client.Create(factories.Post.Has("tags", 3, factories.Tag))23tags := client.CreateMany(3, factories.Tag)45posts := client.CreateMany(5, factories.Post.Attach("tags", tags[0], tags[1], tags[2]))1post := client.Create(factories.Post.Has("tags", 3, factories.Tag))23tags := client.CreateMany(3, factories.Tag)45posts := client.CreateMany(5, factories.Post.Attach("tags", tags[0], tags[1], tags[2]))
The second call links the same three tags to every one of the five posts, and each returned post holds its tags. To set extra columns on the join table, such as whether a tag is pinned to the post, use HasWith, which takes a function that returns each join row's values by the related model's zero-based index. In this example, the first tag is pinned and the second isn't:
1post := client.Create(factories.Post.HasWith("tags", 2, factories.Tag, func(i int) db.Values {2 return db.Values{"pinned": i == 0}3}))1post := client.Create(factories.Post.HasWith("tags", 2, factories.Tag, func(i int) db.Values {2 return db.Values{"pinned": i == 0}3}))
To set join row columns while linking tags that exist, pass AttachWith a map of each tag's key to its values, as model.AttachWith takes:
1posts := client.CreateMany(5, factories.Post.AttachWith("tags", map[int64]db.Values{2 tags[0].ID: {"pinned": true},3 tags[1].ID: {"pinned": false},4}))1posts := client.CreateMany(5, factories.Post.AttachWith("tags", map[int64]db.Values{2 tags[0].ID: {"pinned": true},3 tags[1].ID: {"pinned": false},4}))
Has and Attach also work across morph_to_many and morphed_by_many relationships, and set the type column on each join row.
Recycling models
When a comment belongs to both a user and a post, and the post also belongs to a user, creating a comment with its factory would normally create two separate users. Recycle hands an existing model to every For in the create, including the parents' own factories, wherever that For would otherwise create a model of the same type:
1user := client.Create(factories.User)23comments := client.CreateMany(3, factories.Comment.Recycle(user))1user := client.Create(factories.User)23comments := client.CreateMany(3, factories.Comment.Recycle(user))
Every comment and every post now belongs to user. Recycle also reaches factories you pass to For, so factories.Comment.For("commentable", factories.PublishedPost).Recycle(user) creates a published post by user for each comment. You may also pass Recycle a slice, such as users, to pick one of its models at random for each parent.
After creating callbacks
When creating a model requires work beyond its columns and direct relationships, use AfterCreating to run a function with each created model inside the create's transaction. For example, the Admin factory below finds or creates a shared admin role and links it to every user it creates:
1// database/factories/user.go2var Admin = User.AfterCreating(func(ctx context.Context, user *models.User) error {3 role, _, err := model.FirstOrCreate[models.Role](ctx, db.Values{"name": "admin"}, nil)4 if err != nil {5 return err6 }78 return model.Attach(ctx, user, "roles", role)9})1// database/factories/user.go2var Admin = User.AfterCreating(func(ctx context.Context, user *models.User) error {3 role, _, err := model.FirstOrCreate[models.Role](ctx, db.Values{"name": "admin"}, nil)4 if err != nil {5 return err6 }78 return model.Attach(ctx, user, "roles", role)9})
The function receives each model with the relationships that the factory wrote with Has already loaded. Write with the function's ctx, so the work joins the create's transaction. If the function returns an error, the entire create rolls back and the caller gets the error.
Inserting many rows
When seeding thousands of rows that you don't need back as models, call InsertMany instead of CreateMany. It writes the rows with batched multi-row inserts and returns only an error. For example, this seeder spreads ten thousand comments over ten users and fifty posts:
1func comments(ctx context.Context) error {2 users, err := factories.User.CreateMany(ctx, 10)3 if err != nil {4 return err5 }67 posts, err := factories.Post.Recycle(users).CreateMany(ctx, 50)8 if err != nil {9 return err10 }1112 return factories.Comment.Recycle(users, posts).InsertMany(ctx, 10_000)13}1func comments(ctx context.Context) error {2 users, err := factories.User.CreateMany(ctx, 10)3 if err != nil {4 return err5 }67 posts, err := factories.Post.Recycle(users).CreateMany(ctx, 50)8 if err != nil {9 return err10 }1112 return factories.Comment.Recycle(users, posts).InsertMany(ctx, 10_000)13}
InsertMany sets timestamps, but skips hooks, events, and AfterCreating callbacks. Because it can't create related models, give the factory parents that exist, with Recycle, a model passed to For, or a state that sets the foreign key. Otherwise, InsertMany returns an error before it writes any rows. In a test, client.InsertMany writes the rows the same way and fails the test on an error.
Fake data
Factory definitions, states, and sequences receive a *factory.Faker, which generates realistic random values on every run:
| Method | Returns |
|---|---|
Name(), FirstName(), LastName(), UserName() |
A person's name, or part of one |
Email() |
An address at example.com, example.org, or example.net, which can't receive mail |
Word(), Words(5), Slug(), Sentence(), Paragraph(), Paragraphs(3) |
Lorem ipsum text, and three words joined by hyphens for a slug |
Number(1,, Decimal(1,, Float(0, |
An int, a numeric.Decimal with two digits after its point, or a float64 in the range |
Boolean(25) |
true 25% of the time |
Pick("draft", |
One of the values |
Past(30 * 24 * time.Hour), Future(7 * 24 * time.Hour), Between(start, |
A time.Time before or after the application's time, or between two times |
PastDate(30 * 24 * time.Hour), FutureDate(365 * 24 * time.Hour), DateBetween(start, |
A date.Date before or after today, or between two calendar dates |
Company(), StreetAddress(), City(), State(), PostalCode(), Country(), CountryCode(), PhoneNumber() |
Address book data |
URL(), IPv4(), IPv6() |
Web and network addresses reserved for examples and documentation |
UUID(), ULID(), Alphanumeric(10) |
Identifiers |
Password() |
A hash of "password" |
Unique values
For columns with a unique index, such as email, call Unique() before the method so the faker doesn't give out the same value twice:
1Email: fake.Unique().Email(),1Email: fake.Unique().Email(),
When a generated value repeats several times in a row, Unique() appends a number, such as [email protected], so it never runs out. Unique().Number(..) and Unique().Alphanumeric(..) can't append a number without changing the value's shape, so they panic once their range is nearly exhausted. Note that Unique() only tracks the values the faker generated, not rows already in the database table.
Passwords
Password() returns a bcrypt hash of "password", so a test can log in as a factory's user with that password. The faker hashes the password once with your application's hasher and reuses the hash, so creating 1,000 test users computes one hash instead of 1,000.
Repeatable values
When a test fails on a fake value, you want the next run to fail on that value again. The test client seeds its faker from the test's name, so a test gets the same fake values each time it runs.
If you'd like the same values outside a test, such as in a seeder that builds a demo database, give the factories a faker with a Seed of your own through factory.WithFaker:
1ctx = factory.WithFaker(ctx, &factory.Faker{Hasher: hash.From(ctx), Seed: 42})1ctx = factory.WithFaker(ctx, &factory.Faker{Hasher: hash.From(ctx), Seed: 42})
Testing with factories
In tests, use factories to set up your database, send requests, and verify the result with AssertModelExists, AssertModelMissing, and the other database assertions:
1// tests/feature/posts_test.go2package feature_test34import (5 "fmt"6 "testing"78 "app/database/factories"9 "app/tests"10)1112func TestUsersCanDeleteTheirPosts(t *testing.T) {13 client := tests.New(t)14 user := client.Create(factories.User)15 post := client.Create(factories.Post.For("user", user))1617 client.ActingAs(&user).Delete(fmt.Sprintf("/posts/%d", post.ID)).AssertRedirect("/posts")1819 client.AssertModelMissing(&post)20}1// tests/feature/posts_test.go2package feature_test34import (5 "fmt"6 "testing"78 "app/database/factories"9 "app/tests"10)1112func TestUsersCanDeleteTheirPosts(t *testing.T) {13 client := tests.New(t)14 user := client.Create(factories.User)15 post := client.Create(factories.Post.For("user", user))1617 client.ActingAs(&user).Delete(fmt.Sprintf("/posts/%d", post.ID)).AssertRedirect("/posts")1819 client.AssertModelMissing(&post)20}
Because fake values vary from one test to the next, assert against values your test set, or read them from the models the factory returned, such as user.Email.