What Are Model Factories?
Model factories let you generate fake data for your database tables. They're perfect for testing and seeding your database with realistic records without manually creating each one.
Creating a Factory
Use the artisan command to generate a factory for a model. Laravel places new factories in the database/factories directory.
php artisan make:factory UserFactory
The generated file gives you a define method where you define the default attributes for the model.
Defining Factory Attributes
Inside the factory class, use fake() to generate random data. You can use dozens of methods like name(), email(), and address().
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory
{
protected $model = User::class;
public function definition()
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'password' => bcrypt('password'),
];
}
}
The unique() method ensures no two users share the same email address.
States and Creating Records
Factories support states to define variations of a model. You can also chain count() and create() to insert multiple records at once.
public function definition()
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'password' => bcrypt('password'),
'email_verified_at' => now(),
];
}
public function unverified()
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
Use the factory in your tests or seeders like this:
User::factory()->count(10)->create();
User::factory()->unverified()->create();
Try it Yourself โ
Using Factories in Tests
Factories shine in tests. Instead of building users by hand, call the factory to get a ready-to-use model instance.
use Tests\TestCase;
class ProfileTest extends TestCase
{
public function test_profile_display()
{
$user = User::factory()->create();
$response = $this->get('/profile');
$response->assertStatus(200);
}
}
You can override attributes on the fly by passing an array to create().
$user = User::factory()->create(['name' => 'Sara']);
Factories keep your tests clean, fast, and focused on what actually matters.