跳至正文

Database: Model 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:

go
user := client.Create(factories.User)
posts := client.CreateMany(3, factories.Post.For("user", user))

New applications include a factory for the User model in database/factories/user.go:

go
// database/factories/user.go
package factories

import (
	"go.laravel.com/factory"

	"app/models"
)

// User makes a verified user whose password is "password".
var User = factory.New(func(fake *factory.Faker) models.User {
	return models.User{
		Name:            fake.Name(),
		Email:           fake.Unique().Email(),
		EmailVerifiedAt: new(fake.Now()),
		Password:        fake.Password(),
	}
})

// Unverified makes the user's email address unverified.
func Unverified(_ *factory.Faker, user *models.User) {
	user.EmailVerifiedAt = nil
}

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:

go
// database/factories/post.go
package factories

import (
	"go.laravel.com/factory"

	"app/models"
)

// Post makes a draft post, with a user of its own.
var Post = factory.New(func(fake *factory.Faker) models.Post {
	return models.Post{Title: fake.Sentence()}
}).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:

go
// database/factories/post.go
func Published(fake *factory.Faker, post *models.Post) {
	post.PublishedAt = new(fake.Now().AddDate(0, 0, -1))
}

func Scheduled(fake *factory.Faker, post *models.Post) {
	post.PublishedAt = new(fake.Future(7 * 24 * time.Hour))
}

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:

go
post := 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:

go
// database/factories/post.go
func Titled(title string) func(*factory.Faker, *models.Post) {
	return func(_ *factory.Faker, post *models.Post) {
		post.Title = title
	}
}

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:

go
// database/factories/post.go
var 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:

go
user := client.Create(factories.User)

users := 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:

go
// database/seeders/users.go
package seeders

import (
	"context"

	"app/database/factories"
)

func users(ctx context.Context) error {
	_, err := factories.User.Has("posts", 3, factories.Post).CreateMany(ctx, 10)

	return err
}

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:

go
taylor := client.Create(factories.User, func(u *models.User) {
	u.Name = "Taylor"
	u.Email = "taylor@laravel.com"
})

You may combine overrides with Has to create related models at the same time:

go
user := client.Create(factories.User.Has("posts", 3, factories.Post), func(u *models.User) {
	u.Name = "Taylor"
})

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:

go
post := 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:

go
users := client.CreateMany(10, factories.User.Sequence(func(_ *factory.Faker, user *models.User, i int) {
	if i%2 == 1 {
		user.EmailVerifiedAt = nil
	}
}))

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:

go
user := client.Create(factories.User.Has("posts", 3, factories.Post.State(factories.Published)))

fmt.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:

go
users := client.CreateMany(5, factories.User.Has(
	"posts", 3, factories.Post.Has("comments", 2, factories.Comment),
))

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:

go
user := 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:

go
user := client.Create(factories.User)

posts := client.CreateMany(3, factories.Post.For("user", user))

posts = 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:

go
video := client.Create(factories.Video)

comments := client.CreateMany(3, factories.Comment.For("commentable", video))

comments = 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:

go
post := client.Create(factories.Post.Has("tags", 3, factories.Tag))

tags := client.CreateMany(3, factories.Tag)

posts := 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:

go
post := client.Create(factories.Post.HasWith("tags", 2, factories.Tag, func(i int) db.Values {
	return db.Values{"pinned": i == 0}
}))

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:

go
posts := client.CreateMany(5, factories.Post.AttachWith("tags", map[int64]db.Values{
	tags[0].ID: {"pinned": true},
	tags[1].ID: {"pinned": false},
}))

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:

go
user := client.Create(factories.User)

comments := 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:

go
// database/factories/user.go
var Admin = User.AfterCreating(func(ctx context.Context, user *models.User) error {
	role, _, err := model.FirstOrCreate[models.Role](ctx, db.Values{"name": "admin"}, nil)
	if err != nil {
		return err
	}

	return model.Attach(ctx, user, "roles", role)
})

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:

go
func comments(ctx context.Context) error {
	users, err := factories.User.CreateMany(ctx, 10)
	if err != nil {
		return err
	}

	posts, err := factories.Post.Recycle(users).CreateMany(ctx, 50)
	if err != nil {
		return err
	}

	return factories.Comment.Recycle(users, posts).InsertMany(ctx, 10_000)
}

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:

MethodReturns
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, 100), Decimal(1, 999, 2), Float(0, 5)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", "review", "live")One of the values
Past(30 * 24 * time.Hour), Future(7 * 24 * time.Hour), Between(start, end)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, end)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:

go
Email: fake.Unique().Email(),

When a generated value repeats several times in a row, Unique() appends a number, such as ayla.hirthe.2@example.net, 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:

go
ctx = 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:

go
// tests/feature/posts_test.go
package feature_test

import (
	"fmt"
	"testing"

	"app/database/factories"
	"app/tests"
)

func TestUsersCanDeleteTheirPosts(t *testing.T) {
	client := tests.New(t)
	user := client.Create(factories.User)
	post := client.Create(factories.Post.For("user", user))

	client.ActingAs(&user).Delete(fmt.Sprintf("/posts/%d", post.ID)).AssertRedirect("/posts")

	client.AssertModelMissing(&post)
}

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.