Laravel Seeders and Factories

Lesson 23 of 50 - Learn how to insert sample data into your database using seeders and factories.

46%
1. What Are Seeders and Factories?

Laravel provides seeders and factories to insert sample or initial data into database tables.

Seeders:

Seeders define which records should be inserted into the database. They are useful for adding default categories, test users, courses, and other initial data.

Factories:

Factories define how to generate fake model data. They are useful when you need hundreds or thousands of sample records for testing and development.

For example:

  • A seeder inserts five default courses.
  • A factory generates 100 sample students.
  • A seeder can use a factory to create many records.
2. Create a Student Model and Migration

First, create a Student model with its migration.

php artisan make:model Student -m

Laravel creates a model file and a migration file. Open the generated students table migration and define its columns.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('course')->default('ADCA');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('students');
    }
};

Run the migration:

php artisan migrate

This creates the students table in your configured database. If your project already has this table, do not create a duplicate migration for it.

3. Create a Student Factory

Create a factory for the Student model using Artisan.

php artisan make:factory StudentFactory --model=Student

Open database/factories/StudentFactory.php and define the sample data.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class StudentFactory extends Factory
{
    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'course' => fake()->randomElement([
                'ADCA',
                'Web Development',
                'Tally Prime',
                'Python'
            ]),
        ];
    }
}

fake()->name() generates a fake name. fake()->unique()->safeEmail() generates a unique email for each generated record during the factory run.

The factory fields must match the columns in your students table.

4. Create a Student Seeder

A seeder is a PHP class that inserts data into your database.

Create a seeder using Artisan:

php artisan make:seeder StudentSeeder

Open database/seeders/StudentSeeder.php and add the following code:

<?php

namespace Database\Seeders;

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

class StudentSeeder extends Seeder
{
    public function run(): void
    {
        Student::factory()->count(5)->create();
    }
}

This seeder creates five student records using the Student factory.

Ensure that the Student model uses the HasFactory trait, which Laravel models normally include by default.

5. Run a Seeder

Run an individual seeder using the --class option.

php artisan db:seed --class=StudentSeeder

Laravel executes the StudentSeeder and inserts five sample students.

You can also run the main DatabaseSeeder class:

php artisan db:seed

The main seeder is useful when you want to run several seeders together.

Be careful when running seeders repeatedly. Unless your seeder uses an approach such as updateOrCreate(), running it again may insert duplicate records.

6. Register Seeders in DatabaseSeeder

Open database/seeders/DatabaseSeeder.php to configure which seeders run when you execute php artisan db:seed.

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $this->call([
            StudentSeeder::class,
        ]);
    }
}

You can register multiple seeders in the array. Laravel executes them in the listed order.

$this->call([
    CourseSeeder::class,
    StudentSeeder::class,
    PaymentSeeder::class,
]);

Create each seeder class before adding it to the call() array.

7. Generate Multiple Records with Factories

Factories can generate large numbers of sample records with a single line of code.

Create 100 students:

Student::factory()->count(100)->create();

You can also generate one student:

$student = Student::factory()->create();

To generate a model instance without inserting it into the database, use make():

$student = Student::factory()->make();

You can override selected factory attributes:

Student::factory()->create([
    'name' => 'Rahul Kumar',
    'email' => 'rahul@example.com',
    'course' => 'Python',
]);

The supplied values replace the factory defaults for that generated record.

8. Insert Data Directly Using a Seeder

Factories are not required for every seeder. You can insert fixed data using Eloquent or the query builder.

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class CourseSeeder extends Seeder
{
    public function run(): void
    {
        DB::table('courses')->insert([
            [
                'course_name' => 'ADCA',
                'fee' => 10000,
                'duration' => '12 Months',
            ],
            [
                'course_name' => 'Web Development',
                'fee' => 15000,
                'duration' => '6 Months',
            ],
        ]);
    }
}

This example assumes that the courses table contains course_name, fee, and duration columns.

If the table includes required timestamp columns without defaults, supply their values too. For repeatable seeders, consider updateOrInsert() or updateOrCreate() to avoid duplicates.

9. Important Commands and Practical Assignment

Useful Artisan commands:

Command Purpose
php artisan make:factory StudentFactory --model=Student Create a model factory.
php artisan make:seeder StudentSeeder Create a seeder.
php artisan db:seed Run the main database seeder.
php artisan db:seed --class=StudentSeeder Run one specific seeder.
php artisan migrate:fresh --seed Drop all tables, rerun migrations, and seed the database.

Practical Assignment:

  1. Create a Student model and migration.
  2. Add name, email, and course columns.
  3. Create a StudentFactory that generates fake students.
  4. Create a StudentSeeder that generates five students.
  5. Register StudentSeeder in DatabaseSeeder.
  6. Run the seeder and verify the records in your database.
  7. Generate 100 additional sample students.
  8. Create a CourseSeeder that inserts two fixed courses.

Warning: php artisan migrate:fresh --seed deletes all tables on the selected database connection before recreating them. Use it only in a disposable development or test database where data loss is acceptable.

Quick Quiz

1. What is the main purpose of a Laravel factory?




2. Which command runs database seeders?




3. Which method generates model records and saves them to the database?