“The expert in anything was once a beginner.”
— Helen Hayes
Key Takeaways
Understand the difference between Seeders and Factories in Laravel.
Learn when and how to use create() vs make().
Use FakerPHP methods effectively for fake data.
Apply traditional and modern methods to create seeders and factories.
Use artisan commands efficiently during development.
Index
- Introduction
- When to Use Seeder and Factory
- Traditional vs Modern Usage
- Faker Cheat Sheet — All Available Methods
- Creating Factories
- Creating Seeders
- Handling Relationships
- Real-World Examples
- Advanced Tips
- Testing with Factories
- Difference Between create() and make()
- Summary
- Resources
- Stats
- Interesting Facts
- FAQ’s
- Conclusion
1. Introduction
Seeders and Factories are essential tools in Laravel for generating fake data. They help speed up development and testing by providing sample data to work with. Laravel uses FakerPHP to generate fake information for factories.
Factory: Blueprint to create fake model data.
Seeder: Class used to insert data into the database.
2. When to Use Seeder and Factory
Examples:
- Use factories in tests to create isolated data.
- Use seeders for populating a realistic dataset in local or staging environments.
3. Traditional vs Modern Usage
Before Laravel 8, generating fake data involved a more procedural approach. With Laravel 8+, the system evolved to become more structured, readable, and object-oriented. Let’s look at how factories and seeders have changed over time.
Traditional (Pre-Laravel 8)
factory(User::class, 10)->create();
This method relied on global helper functions and inline logic. It worked, but wasn’t as elegant or flexible.
Modern (Laravel 8+)
php artisan make:factory UserFactory --model=User php artisan make:seeder UserSeeder User::factory()->count(10)->create();
Laravel now uses class-based factories and seeders, making code more readable, testable, and maintainable.
4. Faker Cheat Sheet — All Available Methods
FakerPHP is like a magician for developers—it helps you generate realistic names, addresses, dates, text, and more. Whether you're seeding a development database or writing automated tests, this cheat sheet gives you all the tools to fake it like a pro.
Personal Info
$this->faker->name() $this->faker->firstName() $this->faker->lastName() $this->faker->title() $this->faker->email() $this->faker->unique()->safeEmail() $this->faker->username() $this->faker->password() $this->faker->phoneNumber() $this->faker->address()
Dates & Times
$this->faker->date() $this->faker->dateTime() $this->faker->dateTimeBetween('-1 week', '+1 week') $this->faker->time()
Payments
$this->faker->creditCardNumber() $this->faker->creditCardType() $this->faker->currencyCode() $this->faker->randomFloat(2, 0, 9999)
Location
$this->faker->city() $this->faker->state() $this->faker->country() $this->faker->postcode() $this->faker->latitude() $this->faker->longitude()
Text
$this->faker->word() $this->faker->words(3, true) $this->faker->sentence() $this->faker->paragraph() $this->faker->text(200)
Images & Files
$this->faker->imageUrl(640, 480) $this->faker->image('public/storage/images', 400, 300, null, false)
Numbers
$this->faker->randomDigit() $this->faker->randomNumber() $this->faker->numberBetween(1, 100) $this->faker->randomFloat(2, 1, 1000)
Miscellaneous
$this->faker->uuid() $this->faker->slug() $this->faker->boolean() $this->faker->regexify('[A-Za-z0-9]{10}') $this->faker->url() $this->faker->domainName() $this->faker->company() $this->faker->jobTitle()
5. Creating Factories
php artisan make:factory ProductFactory --model=Product
Sample Factory:
public function definition(): array { return [ 'name' => $this->faker->word(), 'price' => $this->faker->randomFloat(2, 1, 1000), 'description' => $this->faker->sentence(), ]; }
6. Creating Seeders
php artisan make:seeder ProductSeeder
Sample Seeder:
public function run(): void { Product::factory()->count(50)->create(); }
Call Seeder in DatabaseSeeder.php:
$this->call(ProductSeeder::class);
7. Handling Relationships
One-to-One
Profile::factory()->for(User::factory())->create();
One-to-Many
User::factory()->hasPosts(5)->create();
Many-to-Many
Post::factory()->hasTags(3)->create();
8. Real-World Examples
Blog App:
- Users → hasMany → Posts
- Posts → hasMany → Comments
Step-by-Step - Models and Relationships:
// User.php public function posts() { return $this->hasMany(Post::class); } // Post.php public function user() { return $this->belongsTo(User::class); } public function comments() { return $this->hasMany(Comment::class); } // Comment.php public function post() { return $this->belongsTo(Post::class); }
Factory Definitions
// database/factories/UserFactory.php public function definition(): array { return [ 'name' => fake()->name(), 'email' => fake()->unique()->safeEmail(), 'password' => bcrypt('password'), ]; } // database/factories/PostFactory.php public function definition(): array { return [ 'title' => fake()->sentence(), 'body' => fake()->paragraph(5), ]; } // database/factories/CommentFactory.php public function definition(): array { return [ 'content' => fake()->sentence(), ]; }
Seeder Example
// DatabaseSeeder.php public function run(): void { \App\Models\User::factory() ->count(10) ->has( \App\Models\Post::factory() ->count(5) ->has(\App\Models\Comment::factory()->count(3)) ) ->create(); }
E-Commerce:
- Product → belongsTo → Category
- Order → hasMany → OrderItems
- OrderItems -> belongsTo ->Product
Step-by-Step - Models and Relationships:
// Category.php public function products() { return $this->hasMany(Product::class); } // Product.php public function category() { return $this->belongsTo(Category::class); } // Order.php public function items() { return $this->hasMany(OrderItem::class); } // OrderItem.php public function order() { return $this->belongsTo(Order::class); } public function product() { return $this->belongsTo(Product::class); }
Factory Definitions
// CategoryFactory.php public function definition(): array { return [ 'name' => fake()->word(), ]; } // ProductFactory.php public function definition(): array { return [ 'name' => fake()->word(), 'price' => fake()->randomFloat(2, 10, 1000), 'category_id' => Category::factory(), ]; } // OrderFactory.php public function definition(): array { return [ 'user_id' => User::factory(), 'status' => fake()->randomElement(['pending', 'shipped', 'delivered']), ]; } // OrderItemFactory.php public function definition(): array { return [ 'product_id' => Product::factory(), 'quantity' => fake()->numberBetween(1, 5), ]; }
Seeder Example
public function run(): void { // Categories and Products \App\Models\Category::factory() ->count(5) ->has(\App\Models\Product::factory()->count(10)) ->create(); // Orders and Items \App\Models\Order::factory() ->count(20) ->has( \App\Models\OrderItem::factory() ->count(3) ) ->create(); }
Command to Run Seeder:
php artisan migrate:fresh --seed
9. Advanced Tips
Seed Only If Empty
if (User::count() == 0) { User::factory(10)->create(); }
Avoid Production Seeding
if (!app()->isProduction()) { $this->call(DevSeeder::class); }
Migrate & Seed in One Step
php artisan migrate:fresh --seed
10. Testing with Factories
public function test_post_creation() { $user = User::factory()->create(); $post = Post::factory()->for($user)->create(); $this->assertDatabaseHas('posts', ['user_id' => $user->id]); }
11. Difference Between create() and make()
create() Example:
$user = User::factory()->create();
This creates a user and inserts into the database.
make() Example:
$user = User::factory()->make();
This creates a user but doesn’t insert into the database. Useful for testing model logic without hitting the DB.
Human-friendly analogy:
Think of make() as drawing a character on paper (you haven’t created it in real life yet).
create() is like actually 3D printing that character into existence (database).
“Dream big. Start small. Act now.”
— Robin Sharma
12. Summary
**- Factory = Recipe (How to create data)
- Seeder = Chef (Creates and inserts the data)
- Faker = Ingredients (Fake fields)
- make() = Draft copy, not saved
- create() = Final copy, saved to DB**
Use factories for fast, repeatable data creation, especially for tests. Use seeders to load your database with dev data or static reference data.
“Learning never exhausts the mind.”
— Leonardo da Vinci
13. Resources
- Laravel Docs: https://laravel.com/docs/12.x/seeding
- FakerPHP Docs: https://fakerphp.org/
- GitHub Laravel Examples: https://github.com/laravel/laravel/tree/master/database/factories
14. Stats
- Laravel 12 supports class-based seeders and factories by default.(Laravel 12 Documentation — Database: Seeding, Laravel 12 Documentation — Database: Factories)
- FakerPHP has over 50+ methods for generating fake data. (FakerPHP Official Documentation — Formatters)
- Factory usage in Laravel projects increased by 40% since Laravel 8’s class-based system.
15. Interesting Facts
- The Faker library was originally a Ruby gem before being ported to PHP. (Faker Ruby Gem, FakerPHP History)
- Laravel 12 allows factory()->has() relationships that simulate real-world relational data effortlessly. (Laravel Factories — Has Relationships)
- Faker can be customized by locale — meaning you can generate region-specific names, addresses, etc. (FakerPHP Locales)
16. FAQ’s
Q: Can I use factories without seeders?
Yes! Especially useful in unit testing or test classes.
Q: Can I run factories in production?
Not recommended. They are intended for testing/dev environments.
Q: How do I use Faker with a specific locale?
Pass locale to the factory class or override $faker with a new instance.
Q: What if I want unique data each time?
Use methods like $this->faker->unique()->email() to avoid duplicates.
Q: How can I define custom states?
Use the state() method in factories to define preset variations.
17. Conclusion
Laravel Seeders and Factories are indispensable tools for every developer. They ensure smooth development, easy testing, and robust prototyping. By mastering make() vs create(), utilizing Faker’s wide range of data generators, and leveraging artisan commands, you can simulate any data-driven scenario. Whether you’re building a blog, marketplace, or SaaS — this is your cheat code for rapid development.
About the Author: Mayank is a web developer at AddWebSolution, building scalable apps with PHP, Node.js & React. Sharing ideas, code, and creativity.
Top comments (0)