Laravel

Laravel Testing: Factory States and Relationships

December 24, 2025 1 min read 18 views

Advanced factory techniques:

Factory States

public function active(): static
{
    return $this->state(fn (array $attributes) => [
        'is_active' => true,
    ]);
}

Create with Relationships

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

For Relationships

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

Factories make testing with complex data structures simple.

Share this post:

Related Posts

Comments (0)

Please log in to leave a comment. Log in

No comments yet. Be the first to comment!