Model Factories — Generating Fake Data
Factories define how to generate fake model instances using the Faker library. They're used in seeders for development data and in tests for test data. Factories support states (variations) and relationships for creating complex data scenarios.
Factory Definition
// php artisan make:factory PostFactory
class PostFactory extends Factory
{
public function definition(): array
{
return [
'user_id' => User::factory(),
'title' => fake()->sentence(),
'slug' => fake()->slug(),
'body' => fake()->paragraphs(5, true),
'published' => fake()->boolean(70), // 70% true
'published_at' => fake()->dateTimeBetween('-1 year'),
];
}
// States — variations
public function published(): static
{
return $this->state([
'published' => true,
'published_at' => now(),
]);
}
public function draft(): static
{
return $this->state([
'published' => false,
'published_at' => null,
]);
}
}
// Usage
Post::factory()->create(); // One persisted post
Post::factory(10)->create(); // 10 persisted posts
Post::factory()->published()->create(); // Published post
Post::factory()->make(); // In-memory (not saved to DB)Tip
Tip
Practice Model Factories Generating Fake Data in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Local scopes for reusable filters (scopePublished, scopeRecent). Global scopes for always-on filters (multi-tenancy).
Practice Task
Note
Practice Task — (1) Write a working example of Model Factories Generating Fake Data from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Model Factories Generating Fake Data is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.