Difference Between Factories and Seeders in Laravel
Laravel provides both factories and seeders for database population, but they serve different purposes and are used in different scenarios.
Database Factories
Purpose: Factories are used to generate model instances with fake/dummy data, primarily for testing.
Key Characteristics:
Define how models should be generated with fake data
Use Faker library to generate random values
Primarily used in tests and local development
Can create model instances without persisting to database
Support relationships and states (variations)
Example Factory:
// database/factories/UserFactory.php $factory->define(User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => bcrypt('password'), ]; }); // Usage: $user = factory(User::class)->create(); // Persisted to DB $user = factory(User::class)->make(); // Not persisted
Database Seeders
Purpose: Seeders are used to populate your database with specific, predefined data.
Key Characteristics:
Used to insert actual application data (not random/fake)
Often used for initial application setup (admin users, categories, etc.)
Can use factories internally to generate data
Run manually or during deployment
Typically contain specific, predictable data
Example Seeder:
// database/seeds/UsersTableSeeder.php public function run() { // Create specific admin user User::create([ 'name' => 'Admin User', 'email' => 'admin@example.com', 'password' => bcrypt('secret'), 'role' => 'admin' ]); // Use factory to create multiple users factory(User::class, 50)->create(); }
Key Differences
Feature | Factories | Seeders |
---|---|---|
Purpose | Generate fake data for testing | Populate database with real/specific data |
Data Type | Random/Fake data | Specific, predefined data |
Primary Use | Testing environments | Initial application setup |
Persistence | Can create without persisting | Always persists to database |
Relationships | Handles complex model generation | Typically simpler data insertion |
Execution | Called programmatically | Run via artisan command |
When to Use Each
Use Factories when you need:
Test data with random values
Multiple variations of model data
To quickly generate many model instances
Data for your test cases
Use Seeders when you need:
Initial application data (admin accounts, etc.)
Reference data (countries, product categories)
To set up a consistent starting database state
Data that must be exactly the same each time
Working Together
Factories and seeders are often used together:
// In a seeder public function run() { // Create specific records User::create([...]); // Then use factories to generate random data factory(User::class, 100)->create(); }
You would then run the seeder with:
php artisan db:seed # or for a specific seeder php artisan db:seed --class=UsersTableSeeder