Laravel Intermediate Eloquent & Routing · 8 min read

Laravel Seeders and Model Factories

Lesson 10 of 33 in the Laravel learning path.

How do I generate realistic lesson rows for local development?

A factory builds fake, valid model attributes. A seeder calls that factory and writes the rows. Together they give every developer a catalog after migrate, without copying production student data onto a laptop.

Factories belong in local and test databases. They should not run against production unless you have a separate, reviewed command. Use fake() for titles and a short list of real track names so the rows still pass your validation rules.

Syntax & Parameters

Syntax
Lesson::factory()->count(10)->create();

Example

database/factories/LessonFactory.php
<?php

namespace Database\Factories;

use App\Models\Lesson;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

class LessonFactory extends Factory
{
    protected $model = Lesson::class;

    public function definition(): array
    {
        $title = fake()->unique()->words(3, true);

        return [
            'user_id' => User::factory(),
            'title' => ucfirst($title),
            'slug' => str($title)->slug()->toString(),
            'track' => fake()->randomElement(['html', 'css', 'php', 'sql', 'laravel']),
            'seats' => fake()->numberBetween(8, 32),
            'published_at' => fake()->optional()->dateTimeBetween('-1 month', 'now'),
        ];
    }
}

namespace Database\Seeders;

use App\Models\Lesson;
use Illuminate\Database\Seeder;

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

Expected Output

php artisan db:seed --class=LessonSeeder

10 lessons rows
10 users rows, one owner each
slugs such as quiet-river-path
tracks limited to html, css, php, sql, laravel
some published_at values null

Line-by-Line Walkthrough

  1. The factory class names the model it builds.
  2. definition() returns the column array for one row.
  3. fake() is the Laravel 12 helper around Faker. unique() avoids repeated titles in one run.
  4. words(3, true) returns a string, not an array.
  5. User::factory() inside the array creates a user and stores that user's id. The lesson is never orphaned.
  6. The slug is derived from the same title so the public URL matches.
  7. randomElement stays inside the track list the form request allows.
  8. optional() sometimes leaves published_at null, which gives you drafts to test.
  9. The seeder asks for ten models. create() inserts them.
  10. DatabaseSeeder should call $this->call(LessonSeeder::class) so db:seed runs it.
  11. The Lesson model needs the HasFactory trait or the factory() method is missing.
  12. Tests can call Lesson::factory()->create() without going through the seeder.

Common Pitfalls & Security

Seeding production with fake users and fake passwords creates accounts you did not mean to ship. Guard seeders so they refuse to run when the app environment is production, or keep them out of the deploy step.

  • Forgetting HasFactory makes Lesson::factory() throw BadMethodCallException.
  • A factory that sets password to a constant on the User model is a shared secret if that database is copied.
  • unique() on a small faker pool can throw after enough rows. Reset unique or use a sequence.
  • Creating a user per lesson explodes the users table. Pass an existing user id when you want one instructor to own the set.
  • Calling create() in a factory definition that also creates the same model recurses until memory runs out.
  • Do not point a factory at a production connection in phpunit.xml.

Best Practices & Modern Standards

Generate the files with php artisan make:factory LessonFactory --model=Lesson and php artisan make:seeder LessonSeeder. Keep definition() valid for your migration: every required column should be present, and foreign keys should point at real rows.

Laravel 12 uses fake() rather than a $this->faker property. Call factory states, such as Lesson::factory()->published(), when a test needs a lesson that is definitely public. States keep the default definition honest and the special cases named.

Real-World Use

A new teammate clones the course site, runs migrate and db:seed, and opens the catalog. Ten courses already exist, each with an instructor, so the index, the show page, and the enrollment form can be clicked through before any real term data is imported.

Frequently Asked Questions

What is the difference between create and make?

make() builds a model in memory and does not insert it. create() inserts the row. Use make() when a test only needs attributes, and create() when the database must contain the row.

How does the seeder find the factory?

The model uses the HasFactory trait, and the factory class follows the naming convention LessonFactory for Lesson. The protected $model property makes the link explicit.

Can I seed relationships?

Yes. After creating a lesson, call Enrollment::factory()->count(3)->create(['lesson_id' => $lesson->id]) or define a has() relationship on the factory. Set the foreign key. Do not leave it to chance.

Should seeders run in production?

Only seeders that insert required reference data, such as a grading scale, and only when they are idempotent. Demo courses and fake users stay on local and testing databases.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…