Using Factories for Test Data
Model factories generate realistic, randomized test data quickly, replacing tedious hand-written fixtures with a single reusable definition per model.
Defining a Factory
class PostFactory extends Factory
{
public function definition(): array
{
return [
'title' => fake()->sentence(),
'body' => fake()->paragraphs(3, true),
'user_id' => User::factory(),
];
}
}
Using a Factory in Tests
$post = Post::factory()->create();
$posts = Post::factory()->count(5)->create();
Factory States
States let a factory produce variations, such as a published or draft post, without duplicating the whole definition.
public function published(): Factory
{
return $this->state(fn (array $attributes) => [
'published_at' => now(),
]);
}
Post::factory()->published()->create();
With solid testing tools in place, the course now turns to the wider Laravel ecosystem — starting with how packages are installed and managed via Composer.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.
