Laravel 12 Seeding and Factories for Beginners (2025 Guide)

Author

Kritim Yantra

Jul 10, 2025

Laravel 12 Seeding and Factories for Beginners (2025 Guide)

Ever stared at your empty database wondering, “Now what?”

Imagine your database is a garden. You’ve prepared the soil (tables), but there’s nothing growing. That’s where Laravel's seeding and factories come in—they help you plant data quickly so you can see your app come to life.

In this post, we’ll cover:

✅ What is database seeding?
✅ How to create seeders and use them
✅ How to generate fake data with factories
✅ How to link relationships like users and posts
✅ Pro tips to make your development faster

Let’s plant some data! 🌱


🧩 What is Database Seeding?

Database seeding is the process of filling your tables with test or fake data. Laravel makes this easy with:

  • Seeders: Define what data to insert.
  • Factories: Generate random (but realistic) data for any model.

Think of it like setting up demo content so you don’t have to type in everything manually.


🛠️ Step 1: Create a Seeder

Let’s say you want to seed users into your database.

👉 Command to create a seeder:

php artisan make:seeder UserSeeder

This creates a file at:
database/seeders/UserSeeder.php

🧠 Inside UserSeeder.php, add:

use Illuminate\Database\Seeder;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class UserSeeder extends Seeder
{
    public function run(): void
    {
        User::create([
            'name' => 'Jane Doe',
            'email' => 'jane@example.com',
            'password' => Hash::make('password'),
        ]);
    }
}

✅ Run your seeder:

php artisan db:seed --class=UserSeeder

Now your users table has one record. But what if you need 10? 100? That’s where factories shine.


🤖 Step 2: Create a Factory

Factories allow you to automatically generate data for your models using the Faker library.

👉 Create a factory:

php artisan make:factory UserFactory --model=User

🔧 Your factory file: database/factories/UserFactory.php

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    protected $model = \App\Models\User::class;

    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'password' => Hash::make('password'),
            'remember_token' => Str::random(10),
        ];
    }
}

This means every time you run the factory, you get a realistic name, email, and password!


🌱 Step 3: Use Factory in a Seeder

Let’s use the factory to seed 10 users.

📝 Update your UserSeeder.php:

use App\Models\User;

class UserSeeder extends Seeder
{
    public function run(): void
    {
        User::factory()->count(10)->create();
    }
}

Then run:

php artisan db:seed --class=UserSeeder

✅ Now you have 10 random users in your database!


🧠 Example: Seeding Users with Posts

Let’s take this a step further—seed users, and each user gets 3 posts.

👉 Create Post model, migration, and factory:

php artisan make:model Post -mf

In the PostFactory.php:

use Illuminate\Database\Eloquent\Factories\Factory;

class PostFactory extends Factory
{
    public function definition(): array
    {
        return [
            'title' => fake()->sentence(),
            'content' => fake()->paragraph(),
        ];
    }
}

In UserFactory.php, add this relationship:

public function configure(): static
{
    return $this->afterCreating(function (User $user) {
        \App\Models\Post::factory()->count(3)->create(['user_id' => $user->id]);
    });
}

Now every time a user is created via factory, they get 3 posts!


🧩 Step 4: Organize with the Main Seeder

Open DatabaseSeeder.php:

public function run(): void
{
    $this->call([
        UserSeeder::class,
        // Add other seeders here
    ]);
}

Then just run:

php artisan db:seed

Laravel will call all seeders listed.


️ Step 5: Refresh and Seed in One Command

Need to reset everything? Use:

php artisan migrate:fresh --seed

This:

  1. Drops all tables
  2. Runs all migrations
  3. Seeds your database

Perfect for testing from scratch!


🔥 Pro Tips for Clean Seeding

  • 💡 Use states in factories to define types of data:

    public function suspended(): static
    {
        return $this->state(fn () => ['status' => 'suspended']);
    }
    
  • 🤫 Prevent model events during seeding with:

    use Illuminate\Database\Eloquent\Concerns\WithoutModelEvents;
    
    class UserSeeder extends Seeder
    {
        use WithoutModelEvents;
    }
    
  • 🧪 Use factories in tests too! Super helpful for setting up data.


🧠 Real-Life Analogy: Seeders are Scriptwriters, Factories are Actors 🎬

  • Seeders decide what scenes (data) to create.
  • Factories generate the characters (realistic content).
  • Together, they help you rehearse your app before the big launch!

✅ Summary Table

Feature Purpose
php artisan make:seeder Create seed data file
php artisan make:factory Auto-generate realistic fake data
->count(10)->create() Create multiple rows
DatabaseSeeder.php Organize all seeders
php artisan migrate:fresh --seed Refresh DB and repopulate in one command

💬 Try It Yourself

Build a CategorySeeder and use a CategoryFactory to add 10 fake categories.

Bonus: Link it with posts so each category has 5 posts!


🙋️ FAQs

❓1. Can I seed data in production?

Yes, but be careful. Use --force and only if you're sure.

❓2. Can I seed multiple tables?

Absolutely. Just create multiple seeders and call them in DatabaseSeeder.php.

❓3. Can I disable events during seeding?

Yes! Use WithoutModelEvents to prevent triggering observers like creating().


💬 Your Turn

What kind of fake data would help you build your next project faster?
Let us know in the comments below! 👇

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts