Model Factories in Laravel simplify the creation of test data for models by generating realistic dummy data. They are especially useful for seeding databases or writing automated tests.
Model Factories were introduced to make testing and seeding easier by automating the generation of fake data for models.
Create a factory:
php artisan make:factory UserFactory --model=User
In the generated factory:
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory
{
protected $model = \App\Models\User::class;
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'password' => bcrypt('password'),
];
}
}
Use the factory in tests:
$user = User::factory()->create();
Model Factories make testing and seeding easier, ensuring consistent and realistic data generation.