Laravel 10 - Generating Fake Data with Laravel's Faker Library
Laravel provides a built-in way to generate fake data using the Faker library. This is useful for seeding databases during development and testing.
Step 1: Create a Seeder
Run the following Artisan command to create a new seeder class:
This will create a new seeder file at:
📂 database/seeders/UserSeeder.php
Step 2: Add Faker to the Seeder
Open the generated UserSeeder.php file and modify it as follows:
📌 What This Does:
✅ Generates 10 fake users.
✅ Uses Faker::create()
to generate random names, emails, and timestamps.
✅ Hashes the password before inserting it into the database.
Step 3: Run the Seeder
Run the seeder with the following command:
This will insert 10 fake users into your users
table.
Step 4: Use Factories for More Flexibility (Recommended)
Instead of manually inserting fake data using DB::table()
, Laravel provides factories to generate fake data efficiently.
Create a Model Factory
Run the following command to generate a factory for the User
model:
This will create a factory file:
📂 database/factories/UserFactory.php
Define the Fake Data
Modify the factory file:
Use the Factory in the Seeder
Modify UserSeeder.php
to use the factory:
Run the factory-based seeder:
Step 5: Seed the Entire Database
To run all seeders at once, edit DatabaseSeeder.php
:
Then run:
Conclusion
🎯 Using Faker with Laravel allows you to quickly populate your database for development & testing.
✅ Direct Seeder (DB::table()
) - Simple way to insert fake records.
✅ Factory-Based Seeding (User::factory()
) - More powerful and reusable.
✅ Run Seeders using php artisan db:seed
.
Would you like to add fake data for other models like Posts
, Products
, etc.?