Laravel Model Factories: Test Data That Scales
Laravel's model factories solve one of the most tedious parts of writing tests: generating valid, realistic test data. Without factories, tests drown in boilerplate setup code. With well-designed factories, you create precisely the data you need in one line. This guide covers the patterns that make factories maintainable as your test suite grows.
The Problem Factories Solve
Consider a test for post listing that requires an authenticated user with a subscription:
// Without factories — setup dwarfs the actual test
public function test_subscriber_can_see_premium_posts(): void
{
$user = User::create([
'name' => 'Alice',
'email' => 'alice@test.com',
'password' => bcrypt('password'),
'email_verified_at' => now(),
]);
$subscription = Subscription::create([
'user_id' => $user->id,
'plan' => 'pro',
'status' => 'active',
'current_period_ends_at' => now()->addMonth(),
]);
$premiumPost = Post::create([
'title' => 'Premium Content',
'body' => 'Secret content',
'visibility' => 'subscribers_only',
'published_at' => now(),
]);
// FINALLY, the actual test
$response = $this->actingAs($user)->get('/posts');
$response->assertSee('Premium Content');
}
// With factories
public function test_subscriber_can_see_premium_posts(): void
{
$user = User::factory()->subscribed()->create();
Post::factory()->premium()->create(['title' => 'Premium Content']);
$this->actingAs($user)->get('/posts')->assertSee('Premium Content');
}Basic Factory Structure
Factories live in database/factories/:
<?php
// database/factories/UserFactory.php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
protected $model = User::class;
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => bcrypt('password'), // same for all test users
'remember_token' => Str::random(10),
];
}
}Use in tests:
// Create one user (persisted to DB)
$user = User::factory()->create();
// Create without persisting
$user = User::factory()->make();
// Override specific fields
$user = User::factory()->create(['email' => 'specific@example.com']);
// Create multiple
$users = User::factory()->count(5)->create();
// Create collection as array
$users = User::factory()->count(3)->make()->toArray();Factory States
States define named configurations that modify the default definition:
class UserFactory extends Factory
{
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => bcrypt('password'),
'role' => 'user',
'status' => 'active',
];
}
// Admin user
public function admin(): static
{
return $this->state(fn (array $attributes) => [
'role' => 'admin',
]);
}
// Unverified email
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
// Suspended account
public function suspended(): static
{
return $this->state(fn (array $attributes) => [
'status' => 'suspended',
'suspended_at' => now(),
]);
}
// Pro subscriber — chains another factory
public function subscribed(): static
{
return $this->afterCreating(function (User $user) {
Subscription::factory()->active()->create(['user_id' => $user->id]);
});
}
}States are composable:
// Admin who is also unverified (unusual but valid in tests)
$user = User::factory()->admin()->unverified()->create();Factory Relationships
Has Many
class UserFactory extends Factory
{
// ...
public function withPosts(int $count = 3): static
{
return $this->has(Post::factory()->count($count));
}
public function withPublishedPosts(int $count = 3): static
{
return $this->has(
Post::factory()->count($count)->published(),
'posts'
);
}
}
// Usage
$user = User::factory()->withPosts(5)->create();
$user->posts; // 5 Post modelsBelongs To
class PostFactory extends Factory
{
public function definition(): array
{
return [
'user_id' => User::factory(), // auto-creates a user
'title' => fake()->sentence(),
'body' => fake()->paragraphs(3, true),
'status' => 'draft',
'published_at' => null,
];
}
public function published(): static
{
return $this->state(fn () => [
'status' => 'published',
'published_at' => now(),
]);
}
public function premium(): static
{
return $this->state(fn () => [
'visibility' => 'subscribers_only',
]);
}
// Attach to specific user
public function forUser(User $user): static
{
return $this->state(fn () => ['user_id' => $user->id]);
}
}
// Usage — avoids creating extra users
$user = User::factory()->create();
$posts = Post::factory()->count(3)->forUser($user)->published()->create();Many-to-Many
class ArticleFactory extends Factory
{
public function withTags(array $tagNames = ['php', 'testing']): static
{
return $this->afterCreating(function (Article $article) use ($tagNames) {
$tags = collect($tagNames)->map(
fn($name) => Tag::firstOrCreate(['name' => $name])
);
$article->tags()->sync($tags->pluck('id'));
});
}
}
// Usage
$article = Article::factory()->withTags(['laravel', 'testing', 'phpunit'])->create();Sequences
Sequences generate different values for each factory call in a batch:
use Illuminate\Database\Eloquent\Factories\Sequence;
// Cycle through values
$users = User::factory()
->count(3)
->sequence(
['role' => 'admin'],
['role' => 'editor'],
['role' => 'user'],
)
->create();
// First user: admin, second: editor, third: user
// Dynamic sequence
$orders = Order::factory()
->count(5)
->sequence(fn (Sequence $sequence) => [
'order_number' => 'ORD-' . str_pad($sequence->index + 1, 5, '0', STR_PAD_LEFT),
])
->create();
// Orders: ORD-00001, ORD-00002, ORD-00003, ...Faker Customization
Use consistent fake data to make test output readable:
class ProductFactory extends Factory
{
public function definition(): array
{
return [
'name' => fake()->words(3, true),
'sku' => strtoupper(fake()->bothify('??-####')),
'price' => fake()->randomFloat(2, 1.00, 999.99),
'stock' => fake()->numberBetween(0, 1000),
'category' => fake()->randomElement(['Electronics', 'Clothing', 'Books']),
'description' => fake()->paragraph(),
'active' => true,
];
}
public function outOfStock(): static
{
return $this->state(fn () => ['stock' => 0, 'active' => false]);
}
public function expensive(): static
{
return $this->state(fn () => ['price' => fake()->randomFloat(2, 500, 9999)]);
}
}For consistent names across test runs, seed Faker:
// In TestCase setUp — same fake data every run
Faker\Factory::create()->seed(1234);After Creating Hooks
Run code after a model is persisted:
class CompanyFactory extends Factory
{
public function definition(): array
{
return [
'name' => fake()->company(),
'domain' => fake()->domainName(),
];
}
public function withEmployees(int $count = 10): static
{
return $this->afterCreating(function (Company $company) use ($count) {
User::factory()
->count($count)
->create(['company_id' => $company->id]);
// Create an admin
User::factory()
->admin()
->create(['company_id' => $company->id]);
});
}
}
// One call creates company + 10 employees + 1 admin
$company = Company::factory()->withEmployees(10)->create();Using Factories in Tests
class PostControllerTest extends TestCase
{
use RefreshDatabase;
public function test_author_can_delete_own_post(): void
{
$author = User::factory()->create();
$post = Post::factory()->forUser($author)->published()->create();
$this->actingAs($author)
->delete("/posts/{$post->id}")
->assertNoContent();
$this->assertDatabaseMissing('posts', ['id' => $post->id]);
}
public function test_other_users_cannot_delete_post(): void
{
$author = User::factory()->create();
$otherUser = User::factory()->create();
$post = Post::factory()->forUser($author)->create();
$this->actingAs($otherUser)
->delete("/posts/{$post->id}")
->assertForbidden();
$this->assertDatabaseHas('posts', ['id' => $post->id]);
}
public function test_lists_only_published_posts(): void
{
Post::factory()->count(3)->published()->create();
Post::factory()->count(2)->create(); // drafts
$this->get('/posts')
->assertOk()
->assertJsonCount(3, 'data');
}
}Performance: factory() vs create() vs make()
// create() — persists to DB (slow, use for tests needing DB)
$user = User::factory()->create();
// make() — in-memory only (fast, use when DB not needed)
$user = User::factory()->make();
// createQuietly() — skips model events (faster for bulk setup)
$users = User::factory()->count(100)->createQuietly();
// raw() — returns array, no model instantiation
$data = User::factory()->raw();
// ['name' => 'Alice', 'email' => 'alice@example.com', ...]Use make() for unit tests that validate model logic. Use create() only when the test exercises database queries.
Summary
Good factories have three properties: a sensible default that creates valid data without configuration, named states for specific scenarios, and relationship helpers that avoid orphaned model creation. When a factory definition is clear, test setup reads like a specification — "a subscribed user with 3 published posts" — rather than a list of database inserts. That's the signal that your factories are working.
Keep factories in sync with schema migrations. A factory that can't create a valid model silently corrupts your test suite — every test that uses it may be testing nothing.