How to Use Factory in Laravel: Syntax and Examples
In Laravel, use
factory() or model factory classes to create fake data for testing or seeding. Define a factory with Factory classes and call Model::factory() to generate instances quickly.Syntax
Laravel uses factory classes to define how to generate fake data for models. You create a factory class for a model, then use Model::factory() to create or make instances.
Model::factory()->create(): Saves a new model instance to the database.Model::factory()->make(): Creates a new model instance without saving.Model::factory()->count(n): Creates multiple instances.
php
<?php // Example factory usage User::factory()->count(3)->create();
Example
This example shows how to define a factory for a User model and then create 2 users in the database.
php
<?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() { return [ 'name' => $this->faker->name(), 'email' => $this->faker->unique()->safeEmail(), 'email_verified_at' => now(), 'password' => bcrypt('password'), 'remember_token' => Str::random(10), ]; } } // Usage in a seeder or test User::factory()->count(2)->create();
Output
Two new users are saved in the database with fake names and emails.
Common Pitfalls
Common mistakes when using Laravel factories include:
- Not importing the factory class or model correctly.
- Using
factory()helper function which is deprecated in Laravel 8+; useModel::factory()instead. - Forgetting to run
composer dump-autoloadafter creating factory classes. - Not setting the
protected $modelproperty in the factory class.
php
<?php // Wrong (legacy) way - deprecated in Laravel 8+ factory(App\Models\User::class, 3)->create(); // Right way User::factory()->count(3)->create();
Quick Reference
| Method | Description |
|---|---|
Model::factory() | Start a new factory instance for the model |
create() | Create and save a model instance to the database |
make() | Create a model instance without saving |
count(n) | Generate multiple instances |
state() | Modify attributes for the generated model |
has() | Create related models |
Key Takeaways
Use
Model::factory() to generate model instances in Laravel 8 and above.Define factory classes with a
definition() method to specify fake data.Use
create() to save instances and make() to create without saving.Avoid the deprecated
factory() helper function from older Laravel versions.Run
composer dump-autoload after adding new factory classes to autoload them.