Skip to content

Factories

Models

Database: Model Factories

Introduction

When testing your application or seeding your database, you often need realistic records to work with, such as a user and post for an authorization test or fifty users for a local demo. Spelling out every required column in every test adds boilerplate and makes adding a new required column break unrelated tests.

Model factories define sensible defaults for each model so your tests and seeders only specify the columns they care about:

1let user = User::factory().create().await?;
2 
3let posts = Post::factory()
4 .count(3)
5 .for_(Post::user, &user)
6 .create()
7 .await?;
1let user = User::factory().create().await?;
2 
3let posts = Post::factory()
4 .count(3)
5 .for_(Post::user, &user)
6 .create()
7 .await?;

New applications include a factory for the User model right below the model definition:

1// src/models/user.rs
2use laravel::auth::{Authenticatable, RememberToken};
3use laravel::hash::PasswordHash;
4use laravel::model::{Faker, IntoCreate, create, factory, model};
5use laravel::time::Timestamp;
6 
7#[model]
8#[derive(Authenticatable)]
9pub struct User {
10 pub id: i64,
11 pub name: String,
12 pub email: String,
13 pub email_verified_at: Option<Timestamp>,
14 #[serde(skip)]
15 pub password: PasswordHash,
16 #[serde(skip)]
17 pub remember_token: Option<RememberToken>,
18 pub created_at: Timestamp,
19 pub updated_at: Timestamp,
20}
21 
22#[factory(User)]
23pub struct UserFactory;
24 
25impl UserFactory {
26 fn definition(fake: &mut Faker) -> impl IntoCreate<User> {
27 create!(User {
28 name: fake.name(),
29 email: fake.unique().email(),
30 email_verified_at: laravel::now(),
31 password: "password",
32 })
33 }
34 
35 pub fn unverified(self) -> Self {
36 self.state(|user, _| user.email_verified_at(None::<Timestamp>))
37 }
38}
1// src/models/user.rs
2use laravel::auth::{Authenticatable, RememberToken};
3use laravel::hash::PasswordHash;
4use laravel::model::{Faker, IntoCreate, create, factory, model};
5use laravel::time::Timestamp;
6 
7#[model]
8#[derive(Authenticatable)]
9pub struct User {
10 pub id: i64,
11 pub name: String,
12 pub email: String,
13 pub email_verified_at: Option<Timestamp>,
14 #[serde(skip)]
15 pub password: PasswordHash,
16 #[serde(skip)]
17 pub remember_token: Option<RememberToken>,
18 pub created_at: Timestamp,
19 pub updated_at: Timestamp,
20}
21 
22#[factory(User)]
23pub struct UserFactory;
24 
25impl UserFactory {
26 fn definition(fake: &mut Faker) -> impl IntoCreate<User> {
27 create!(User {
28 name: fake.name(),
29 email: fake.unique().email(),
30 email_verified_at: laravel::now(),
31 password: "password",
32 })
33 }
34 
35 pub fn unverified(self) -> Self {
36 self.state(|user, _| user.email_verified_at(None::<Timestamp>))
37 }
38}

A factory is a unit struct annotated with #[factory(User)], which generates User::factory() on the model. Its definition method receives a Faker instance for generating fake data and returns the default attributes as a create! expression. Additional methods on the factory define reusable states.

Because User::factory().create() produces the same create builder as create!(User { .. }), model hooks, events, and nested creates all run automatically. Each create() call executes inside a single transaction, so parent and child records commit or roll back together.

Defining factories

Where factories live

Define each model's factory directly below its model struct (as User does) and re-export it from src/models/mod.rs:

1// src/models/mod.rs
2mod post;
3mod user;
4 
5pub use post::{Post, PostFactory};
6pub use user::{User, UserFactory};
1// src/models/mod.rs
2mod post;
3mod user;
4 
5pub use post::{Post, PostFactory};
6pub use user::{User, UserFactory};

Keeping the factory next to the model means that when you add a new required column, the compiler error pointing to the factory is right in the same file.

Callers using User::factory() only need to import User; exporting UserFactory allows helper functions and seeders to reference the factory type directly.

Parents in a definition

Like any create! call, a factory definition must provide every required column without a database default, ensuring your factories stay in sync with your schema at compile time. For a #[belongs_to] relationship, you may assign another factory so each created post automatically gets its own author:

1// src/models/post.rs
2use laravel::model::{Faker, IntoCreate, create, factory};
3 
4use crate::models::User;
5 
6#[factory(Post)]
7pub struct PostFactory;
8 
9impl PostFactory {
10 fn definition(fake: &mut Faker) -> impl IntoCreate<Post> {
11 create!(Post {
12 user: User::factory(),
13 title: fake.sentence(),
14 body: fake.paragraph(),
15 })
16 }
17}
1// src/models/post.rs
2use laravel::model::{Faker, IntoCreate, create, factory};
3 
4use crate::models::User;
5 
6#[factory(Post)]
7pub struct PostFactory;
8 
9impl PostFactory {
10 fn definition(fake: &mut Faker) -> impl IntoCreate<Post> {
11 create!(Post {
12 user: User::factory(),
13 title: fake.sentence(),
14 body: fake.paragraph(),
15 })
16 }
17}

The parent user is inserted alongside the post in the same transaction. Whenever a caller supplies an existing user through an override, for_, or has, Laravel skips the definition's User::factory() completely.

#[morph_to] relationships also accept a factory, so a comment's definition may set commentable: Post::factory() while an override like create!(Comment::factory() { commentable: &video }) attaches the comment to a video instead.

Factory states

Factory states let you define reusable modifications to a model's default attributes, such as a published post or a suspended user. Write each state as a method returning Self that calls self.state(...), passing a closure that receives the create builder and Faker:

1// src/models/post.rs
2use laravel::time::ToSpan;
3 
4impl PostFactory {
5 pub fn published(self) -> Self {
6 self.state(|post, _| post.published_at(laravel::now()))
7 }
8 
9 pub fn scheduled(self) -> Self {
10 self.state(|post, fake| post.published_at(fake.future(1.week())))
11 }
12}
1// src/models/post.rs
2use laravel::time::ToSpan;
3 
4impl PostFactory {
5 pub fn published(self) -> Self {
6 self.state(|post, _| post.published_at(laravel::now()))
7 }
8 
9 pub fn scheduled(self) -> Self {
10 self.state(|post, fake| post.published_at(fake.future(1.week())))
11 }
12}

States run after definition in the order you chain them, with later states overriding earlier values for the same column. Because the closure executes once per created row, capture any state parameter by value and pass it to the column setter by reference:

1impl PostFactory {
2 pub fn titled(self, title: impl Into<String>) -> Self {
3 let title = title.into();
4 self.state(move |post, _| post.title(&title))
5 }
6}
1impl PostFactory {
2 pub fn titled(self, title: impl Into<String>) -> Self {
3 let title = title.into();
4 self.state(move |post, _| post.title(&title))
5 }
6}

For a one-off tweak inside a test, call state inline:

1let post = Post::factory()
2 .state(|post, _| post.title("Draft"))
3 .create()
4 .await?;
1let post = Post::factory()
2 .state(|post, _| post.title("Draft"))
3 .create()
4 .await?;

Creating models with factories

Call create() and await it to insert a model and return it, or chain count(n) before create() to insert multiple records and return a Vec:

1use app::models::User;
2 
3let user = User::factory().create().await?;
4 
5let users = User::factory()
6 .unverified()
7 .count(3)
8 .create()
9 .await?;
1use app::models::User;
2 
3let user = User::factory().create().await?;
4 
5let users = User::factory()
6 .unverified()
7 .count(3)
8 .create()
9 .await?;

Always call custom factory state methods before count. Calling count transitions the builder into Many<User>, which supports state, sequence, and relationship helpers, but not custom methods defined on UserFactory (so User::factory().count(3).unverified() will not compile).

Model hooks and Created events fire for every created record. To suppress events when creating models, chain quietly():

1let users = User::factory().count(50).create().quietly().await?;
1let users = User::factory().count(50).create().quietly().await?;

When running factories inside a database seeder, you can mute model events for the entire seeder using #[seeder(without_events)] instead of chaining quietly() on each call.

Overriding columns

To override specific attributes when creating a record, pass the factory to create!. Column names and value types are still checked at compile time:

1use laravel::model::create;
2 
3let taylor = create!(User::factory() {
4 name: "Taylor",
5 email: "[email protected]",
6})
7.await?;
1use laravel::model::create;
2 
3let taylor = create!(User::factory() {
4 name: "Taylor",
5 email: "[email protected]",
6})
7.await?;

You may also chain column setters directly after create(), which pairs naturally with factory states:

1let abigail = User::factory()
2 .unverified()
3 .create()
4 .name("Abigail")
5 .await?;
1let abigail = User::factory()
2 .unverified()
3 .create()
4 .name("Abigail")
5 .await?;

You can combine attribute overrides with has to create related models at the same time:

1let user = create!(User::factory() { name: "Taylor" })
2 .has(User::posts, Post::factory().count(3))
3 .await?;
1let user = create!(User::factory() { name: "Taylor" })
2 .has(User::posts, Post::factory().count(3))
3 .await?;

To create multiple records with distinct overrides, pass a list to create!:

1let users = create!([
2 User::factory() { name: "Taylor" },
3 User::factory() { name: "Abigail" },
4])
5.await?;
1let users = create!([
2 User::factory() { name: "Taylor" },
3 User::factory() { name: "Abigail" },
4])
5.await?;

Sequences

Use sequence when an attribute should vary from one generated record to the next. The closure receives the create builder, Faker, and the zero-based row index. For example, this creates ten users with every second user verified:

1let users = User::factory()
2 .count(10)
3 .sequence(|user, _, index| {
4 user.email_verified_at((index % 2 == 0).then(laravel::now))
5 })
6 .create()
7 .await?;
1let users = User::factory()
2 .count(10)
3 .sequence(|user, _, index| {
4 user.email_verified_at((index % 2 == 0).then(laravel::now))
5 })
6 .create()
7 .await?;

Factory relationships

Has one and has many

Use has to create related child models for each parent record through a #[has_one] or #[has_many] relationship:

1let user = User::factory()
2 .has(User::posts, Post::factory().published().count(3))
3 .create()
4 .await?;
5 
6assert_eq!(user.posts.len(), 3);
1let user = User::factory()
2 .has(User::posts, Post::factory().published().count(3))
3 .create()
4 .await?;
5 
6assert_eq!(user.posts.len(), 3);

Laravel sets each child's foreign key to the new parent's ID and hydrates the relationship on the returned models automatically, so user.posts holds the three posts and each post's user holds the new user without extra queries. Children created through #[morph_one] or #[morph_many] also populate their #[morph_to] field automatically. You may nest has calls and combine them with count to build multi-level trees:

1let users = User::factory()
2 .count(5)
3 .has(
4 User::posts,
5 Post::factory()
6 .count(3)
7 .has(Post::comments, Comment::factory().count(2)),
8 )
9 .create()
10 .await?;
1let users = User::factory()
2 .count(5)
3 .has(
4 User::posts,
5 Post::factory()
6 .count(3)
7 .has(Post::comments, Comment::factory().count(2)),
8 )
9 .create()
10 .await?;

This creates 5 users, 15 posts, and 30 comments in one transaction. Passing a factory for the wrong model type, such as has(User::posts, Comment::factory()), fails to compile.

Because a #[has_one] relationship holds a single record (such as profile: HasOne<Option<Profile>>), pass a single factory without count:

1let user = User::factory()
2 .has(User::profile, Profile::factory())
3 .create()
4 .await?;
1let user = User::factory()
2 .has(User::profile, Profile::factory())
3 .create()
4 .await?;

Belongs to

Use for_ to associate created models with a shared parent through a #[belongs_to] relationship. It accepts either an existing model or another factory:

1let user = User::factory().create().await?;
2 
3let posts = Post::factory()
4 .count(3)
5 .for_(Post::user, &user)
6 .create()
7 .await?;
8 
9let posts = Post::factory()
10 .count(3)
11 .for_(Post::user, User::factory().unverified())
12 .create()
13 .await?;
1let user = User::factory().create().await?;
2 
3let posts = Post::factory()
4 .count(3)
5 .for_(Post::user, &user)
6 .create()
7 .await?;
8 
9let posts = Post::factory()
10 .count(3)
11 .for_(Post::user, User::factory().unverified())
12 .create()
13 .await?;

The first call associates all three posts with user. The second creates a single unverified user and assigns all three posts to that user. In both cases, the definition's default user: User::factory() is skipped so no extra users are created.

for_ also supports #[morph_to] relationships with any target model or factory listed in the polymorphic enum:

1let comments = Comment::factory()
2 .count(3)
3 .for_(Comment::commentable, &video)
4 .create()
5 .await?;
6 
7let comments = Comment::factory()
8 .count(3)
9 .for_(Comment::commentable, Post::factory())
10 .create()
11 .await?;
1let comments = Comment::factory()
2 .count(3)
3 .for_(Comment::commentable, &video)
4 .create()
5 .await?;
6 
7let comments = Comment::factory()
8 .count(3)
9 .for_(Comment::commentable, Post::factory())
10 .create()
11 .await?;

The first argument must be a #[belongs_to] or #[morph_to] relationship descriptor on the model (such as Post::user), and passing a create! expression instead of a model or factory fails to compile. If a model has multiple relationships to the same target type, such as a category's parent and children, passing the wrong direction (Category::children) panics with a message pointing to the fix.

Belongs to many

When called on a #[belongs_to_many] relationship, has either creates new related models and attaches them via the join table, or attaches existing models:

1let post = Post::factory()
2 .has(Post::tags, Tag::factory().count(3))
3 .create()
4 .await?;
5 
6let tags = Tag::factory().count(3).create().await?;
7 
8let posts = Post::factory()
9 .count(5)
10 .has(Post::tags, &tags)
11 .create()
12 .await?;
1let post = Post::factory()
2 .has(Post::tags, Tag::factory().count(3))
3 .create()
4 .await?;
5 
6let tags = Tag::factory().count(3).create().await?;
7 
8let posts = Post::factory()
9 .count(5)
10 .has(Post::tags, &tags)
11 .create()
12 .await?;

The second call attaches the same three tags to every one of the five posts, with post.tags populated on each returned post. Just like attach, has accepts a single model, an array, a Vec, or a slice by value or by reference. To populate extra columns on the join table, pass a tuple containing the related models and db::values!:

1use laravel::db;
2 
3let post = Post::factory()
4 .has(Post::tags, (Tag::factory().count(2), db::values! { pinned: true }))
5 .create()
6 .await?;
1use laravel::db;
2 
3let post = Post::factory()
4 .has(Post::tags, (Tag::factory().count(2), db::values! { pinned: true }))
5 .create()
6 .await?;

If the join columns depend on each attached model's position, pass a closure receiving the zero-based index instead:

1let post = Post::factory()
2 .has(
3 Post::tags,
4 (&tags, |index: usize| db::values! { pinned: index == 0 }),
5 )
6 .create()
7 .await?;
1let post = Post::factory()
2 .has(
3 Post::tags,
4 (&tags, |index: usize| db::values! { pinned: index == 0 }),
5 )
6 .create()
7 .await?;

For relationships declared with a typed join row such as BelongsToMany<Role, Membership>, pass the join attributes using joined!:

1use laravel::model::joined;
2 
3let user = User::factory()
4 .has(
5 User::roles,
6 (Role::factory(), joined!(Membership { level: "owner" })),
7 )
8 .create()
9 .await?;
1use laravel::model::joined;
2 
3let user = User::factory()
4 .has(
5 User::roles,
6 (Role::factory(), joined!(Membership { level: "owner" })),
7 )
8 .create()
9 .await?;

Because the factory does not re-query typed join rows after inserting them, call load(User::roles) before reading join row fields.

has also works across #[morph_to_many] and #[morphed_by_many] relationships and populates the type column on each join row. Relationships declared with a join row, such as MorphToMany<Tag, Tagging>, do not hydrate the created tags automatically, so call load(Post::tags) before reading them.

Recycling models

When a comment references both a post and a user, and the post also references a user, Comment::factory().create() would normally create two separate users. recycle reuses an existing model across every factory in the create tree, including nested parents and children, wherever that model type would otherwise be created:

1let user = User::factory().create().await?;
2 
3let comments = Comment::factory()
4 .count(3)
5 .recycle(&user)
6 .create()
7 .await?;
1let user = User::factory().create().await?;
2 
3let comments = Comment::factory()
4 .count(3)
5 .recycle(&user)
6 .create()
7 .await?;

Every comment and every post is now associated with user. recycle also reaches factories passed to for_, so Comment::factory().for_(Comment::post, Post::factory()).recycle(&user) creates one post for user. You may also pass a slice such as &users to pick one model at random for each parent.

You may also call recycle on a create! override:

1let comment = create!(Comment::factory() { body: "Thanks!" })
2 .recycle(&user)
3 .await?;
1let comment = create!(Comment::factory() { body: "Thanks!" })
2 .recycle(&user)
3 .await?;

After creating callbacks

When creating a row requires extra work beyond its columns or direct relationships, use after_creating to run an async closure with each created model inside the factory's transaction. For example, the admin state below finds or creates a shared "admin" role and attaches it to every user created with User::factory().admin():

1// src/models/user.rs
2use crate::models::Role;
3 
4impl UserFactory {
5 pub fn admin(self) -> Self {
6 self.after_creating(|user| async move {
7 let role = Role::first_or_create(
8 Role::name.eq("admin"),
9 create!(Role { name: "admin" }),
10 )
11 .await?;
12 
13 user.roles().attach(&role).await?;
14 
15 Ok(())
16 })
17 }
18}
1// src/models/user.rs
2use crate::models::Role;
3 
4impl UserFactory {
5 pub fn admin(self) -> Self {
6 self.after_creating(|user| async move {
7 let role = Role::first_or_create(
8 Role::name.eq("admin"),
9 create!(Role { name: "admin" }),
10 )
11 .await?;
12 
13 user.roles().attach(&role).await?;
14 
15 Ok(())
16 })
17 }
18}

The closure receives each model with any factory-created relationships already loaded. If the callback returns an error, the entire transaction rolls back and the error is returned to the caller.

Inserting many rows

When seeding thousands of rows that you do not need returned as hydrated models, call insert() instead of create(). It writes rows using batched multi-row INSERT statements and returns ():

1let users = User::factory().count(10).create().await?;
2let posts = Post::factory().count(50).recycle(&users).create().await?;
3 
4Comment::factory()
5 .count(10_000)
6 .recycle(&users)
7 .recycle(&posts)
8 .insert()
9 .await?;
1let users = User::factory().count(10).create().await?;
2let posts = Post::factory().count(50).recycle(&users).create().await?;
3 
4Comment::factory()
5 .count(10_000)
6 .recycle(&users)
7 .recycle(&posts)
8 .insert()
9 .await?;

insert sets timestamps automatically, but skips model hooks, events, and after_creating callbacks. Because it cannot create nested parent rows, supply existing parents via recycle, for_, or explicit foreign keys in a state; otherwise the call returns an error before executing.

Fake data

Factory definitions, states, and sequences receive a Faker instance that generates realistic random values on every run:

Method Returns
name(), first_name(), last_name(), user_name() 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 hyphenated slugs
number(1..=100), decimal(1..=999, 2), float(0.0..=5.0) An integer, Decimal, or f64 in the range
boolean(25) true 25% of the time
pick(&["draft", "review", "live"]) One of the items
past(30.days()), future(1.week()), between(start, end) A Timestamp before, after, or between times
past_date(30.days()), future_date(1.year()), date_between(start, end) A Date before, after, or between calendar dates
company(), street_address(), city(), state(), postal_code(), country(), country_code(), phone_number() Address book data
url(), ipv4(), ipv6() Web and network addresses reserved for examples and documentation
uuid(), ulid(), alphanumeric(10) Identifiers

Unique values

For columns with a unique index, such as email, chain unique() on Faker so generated values do not repeat within the running application:

1create!(User {
2 name: fake.name(),
3 email: fake.unique().email(),
4 password: "password",
5})
1create!(User {
2 name: fake.name(),
3 email: fake.unique().email(),
4 password: "password",
5})

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(..) cannot append a suffix and panic once their range is nearly exhausted. Note that unique() only tracks values generated in memory, not existing rows already in the database table.

Passwords

When a factory assigns a plain-text string to a PasswordHash column (such as password: "password"), Laravel caches the bcrypt hash per application so creating 1,000 test users computes only one hash instead of 1,000. Calls to create! outside a factory always compute a fresh hash.

Repeatable values

When a test fails on a fake value, you want the next run to fail on that value again. Tests marked with #[laravel::test] seed the application's faker from the test's name, so a test gets the same fake values each time it runs.

If you'd like repeatable values outside a test, such as in a seeder that builds a demo database, call Faker::seed with a seed of your own:

1use laravel::model::Faker;
2 
3Faker::seed(42);
1use laravel::model::Faker;
2 
3Faker::seed(42);

Testing with factories

In tests, use factories to set up your database state, send requests, and verify the result with assert_model_exists, assert_model_missing, and the other database assertions:

1// tests/posts.rs
2use laravel::testing::prelude::*;
3 
4use app::models::{Post, User};
5 
6#[laravel::test]
7async fn users_can_delete_their_posts(app: Application) -> laravel::Result<()> {
8 let user = User::factory().create().await?;
9 let post = Post::factory().for_(Post::user, &user).create().await?;
10 
11 app.delete(&format!("/posts/{}", post.id))
12 .acting_as(&user)
13 .await
14 .assert_redirect();
15 
16 app.assert_model_missing(&post).await;
17 
18 Ok(())
19}
1// tests/posts.rs
2use laravel::testing::prelude::*;
3 
4use app::models::{Post, User};
5 
6#[laravel::test]
7async fn users_can_delete_their_posts(app: Application) -> laravel::Result<()> {
8 let user = User::factory().create().await?;
9 let post = Post::factory().for_(Post::user, &user).create().await?;
10 
11 app.delete(&format!("/posts/{}", post.id))
12 .acting_as(&user)
13 .await
14 .assert_redirect();
15 
16 app.assert_model_missing(&post).await;
17 
18 Ok(())
19}

Because fake values vary on every test run, assert against values your test set explicitly or read them from the returned factory models (such as user.email).