DEV Community

Cover image for Laravel Seeders & Factories —How to Generate Fake Data for Development

Laravel Seeders & Factories —How to Generate Fake Data for Development

“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

  1. Introduction
  2. When to Use Seeder and Factory
  3. Traditional vs Modern Usage
  4. Faker Cheat Sheet — All Available Methods
  5. Creating Factories
  6. Creating Seeders
  7. Handling Relationships
  8. Real-World Examples
  9. Advanced Tips
  10. Testing with Factories
  11. Difference Between create() and make()
  12. Summary
  13. Resources
  14. Stats
  15. Interesting Facts
  16. FAQ’s
  17. 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(); 
Enter fullscreen mode Exit fullscreen mode

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(); 
Enter fullscreen mode Exit fullscreen mode

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() 
Enter fullscreen mode Exit fullscreen mode

Dates & Times

$this->faker->date() $this->faker->dateTime() $this->faker->dateTimeBetween('-1 week', '+1 week') $this->faker->time() 
Enter fullscreen mode Exit fullscreen mode

Payments

$this->faker->creditCardNumber() $this->faker->creditCardType() $this->faker->currencyCode() $this->faker->randomFloat(2, 0, 9999) 
Enter fullscreen mode Exit fullscreen mode

Location

$this->faker->city() $this->faker->state() $this->faker->country() $this->faker->postcode() $this->faker->latitude() $this->faker->longitude() 
Enter fullscreen mode Exit fullscreen mode

Text

$this->faker->word() $this->faker->words(3, true) $this->faker->sentence() $this->faker->paragraph() $this->faker->text(200) 
Enter fullscreen mode Exit fullscreen mode

Images & Files

$this->faker->imageUrl(640, 480) $this->faker->image('public/storage/images', 400, 300, null, false) 
Enter fullscreen mode Exit fullscreen mode

Numbers

$this->faker->randomDigit() $this->faker->randomNumber() $this->faker->numberBetween(1, 100) $this->faker->randomFloat(2, 1, 1000) 
Enter fullscreen mode Exit fullscreen mode

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() 
Enter fullscreen mode Exit fullscreen mode

5. Creating Factories

php artisan make:factory ProductFactory --model=Product 
Enter fullscreen mode Exit fullscreen mode

Sample Factory:

public function definition(): array { return [ 'name' => $this->faker->word(), 'price' => $this->faker->randomFloat(2, 1, 1000), 'description' => $this->faker->sentence(), ]; } 
Enter fullscreen mode Exit fullscreen mode

6. Creating Seeders

php artisan make:seeder ProductSeeder 
Enter fullscreen mode Exit fullscreen mode

Sample Seeder:

public function run(): void { Product::factory()->count(50)->create(); } 
Enter fullscreen mode Exit fullscreen mode

Call Seeder in DatabaseSeeder.php:

$this->call(ProductSeeder::class); 
Enter fullscreen mode Exit fullscreen mode

7. Handling Relationships

One-to-One

Profile::factory()->for(User::factory())->create(); 
Enter fullscreen mode Exit fullscreen mode

One-to-Many

User::factory()->hasPosts(5)->create(); 
Enter fullscreen mode Exit fullscreen mode

Many-to-Many

Post::factory()->hasTags(3)->create(); 
Enter fullscreen mode Exit fullscreen mode

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); } 
Enter fullscreen mode Exit fullscreen mode

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(), ]; } 
Enter fullscreen mode Exit fullscreen mode

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(); } 
Enter fullscreen mode Exit fullscreen mode

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); } 
Enter fullscreen mode Exit fullscreen mode

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), ]; } 
Enter fullscreen mode Exit fullscreen mode

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(); } 
Enter fullscreen mode Exit fullscreen mode

Command to Run Seeder:

php artisan migrate:fresh --seed 
Enter fullscreen mode Exit fullscreen mode

9. Advanced Tips

Seed Only If Empty

if (User::count() == 0) { User::factory(10)->create(); } 
Enter fullscreen mode Exit fullscreen mode

Avoid Production Seeding

if (!app()->isProduction()) { $this->call(DevSeeder::class); } 
Enter fullscreen mode Exit fullscreen mode

Migrate & Seed in One Step

php artisan migrate:fresh --seed 
Enter fullscreen mode Exit fullscreen mode

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]); } 
Enter fullscreen mode Exit fullscreen mode

11. Difference Between create() and make()

create() Example:

$user = User::factory()->create(); 
Enter fullscreen mode Exit fullscreen mode

This creates a user and inserts into the database.

make() Example:

$user = User::factory()->make(); 
Enter fullscreen mode Exit fullscreen mode

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

14. Stats

15. Interesting Facts

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)