Skip to content

Factory Chaining Cheatsheet

Factory Chaining Cheatsheet

🧱 Basic Factory Use

User::factory()->create(); // creates 1 user
User::factory()->count(5)->create(); // creates 5 users
User::factory()->make(); // creates, but doesn't save

🎯 Override Attributes

User::factory()->create([
'name' => 'Michael',
'email' => 'm@example.com',
]);

πŸ§ͺ Using state()

Reusable or chainable values:

User::factory()
->state([
'status' => 'active',
])
->create();

Or using a closure for more logic:

User::factory()
->state(function (array $attributes) {
return [
'email' => Str::random(5) . '@example.com',
];
})
->create();

πŸ”— .for() – BelongsTo Relationships

Post::factory()
->for(User::factory())
->create();

You can also pass an existing model:

$user = User::first();
Post::factory()->for($user)->create();

This will automatically set user_id (foreign key) on the post.

🧬 .has() – HasMany / HasOne Relationships

User::factory()
->has(Post::factory()->count(3))
->create();

You can go deeper:

User::factory()
->has(
Post::factory()
->count(3)
->has(Comment::factory()->count(5))
)
->create()

πŸ— .hasAttached() – Many-to-Many Relationships

Post::factory()
->hasAttached(Tag::factory()->count(3))
->create();

With pivot data:

Post::factory()
->hasAttached(
Tag::factory()->count(3),
['attached_at' => now()]
)
->create();

βš™οΈ Setting Foreign Keys Manually in Create

$author = Author::factory()->create();
Book::factory()->count(10)->create([
'author_id' => $author->id,
]);

Useful if you’re inside loops and already have the parent instance.

🧡 Nested Loop Seeding (Pattern)

$users = User::factory()->count(5)->create();
$users->each(function ($user) {
Post::factory()
->count(rand(1, 5))
->for($user)
->create()
->each(function ($post) {
Comment::factory()
->count(rand(1, 3))
->for($post)
->create();
});
});

🧰 Making Without Saving (useful for manipulation)

$post = Post::factory()->make([
'title' => 'Draft Post',
]);
// $post is not saved yet
$post->save();

πŸ§ͺ Example: Factory for Polymorphic Relations

Comment::factory()
->for(User::factory(), 'commentable') // if commentable is the morphTo
->create();

Or use .morphTo() logic in factory directly (advanced).

πŸ“Ž Tips

  • make() creates unsaved instance
  • create() persists to DB
  • Use createQuietly() if you want to skip events
  • Use sequence() to cycle through a series of values
  • Use afterCreating() and afterMaking() hooks inside factories for auto-seeding related models