Factory Chaining Cheatsheet
Factory Chaining Cheatsheet
π§± Basic Factory Use
User::factory()->create(); // creates 1 userUser::factory()->count(5)->create(); // creates 5 usersUser::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 instancecreate()
persists to DB- Use
createQuietly()
if you want to skip events - Use
sequence()
to cycle through a series of values - Use
afterCreating()
andafterMaking()
hooks inside factories for auto-seeding related models