Laravel 12 Database Seeder Example

In this Laravel 12 tutorial, you’ll learn step by step how to create laravel 12 database seeder example and run database seeders in Laravel 12.

When building a Laravel project, you often need to populate your database with test data such as dummy users, posts, or products for development or testing.

Laravel provides an elegant way to do this using database seeders.

Why Use Database Seeders?

Database seeders are essential for several reasons:

  • Development Efficiency: Quickly populate your database with test data without manual insertion
  • Admin Users: Create default admin users for applications without public registration
  • Default Settings: Insert default configuration values and system settings
  • Testing: Generate consistent test data for feature testing and unit tests
  • Onboarding: Set up sample data for new team members to understand the database structure
  • Reproducibility: Ensure everyone on your team has the same initial database state

Step 1: Install Laravel Project

First, let’s install a fresh Laravel project. If you already have Laravel installed, you can skip this step.

composer create-project laravel/laravel laravel-seeder-example

This command will download and install the latest version of Laravel in a folder named laravel-seeder-example.

Read Also :Laravel 12 Create, Skip, Run and Rollback Migrations

Step 2: Create Migration and Model

Now, Run the command given below to create migration and model for category table:

php artisan make:model Category -m

Now, open the Category migration file and update it with the following columns:

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->boolean('status')->default(true);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('categories');
    }
};

Run the command given below to create table:

php artisan migrate

Now , Open App\Models\Category.php and update with the following:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Category extends Model
{
     /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory;
    
        /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'status',
    ];
}

⚠️ Important Note

Make sure to import the HasFactory (use Illuminate\Database\Eloquent\Factories\HasFactory) trait in your model if you plan to use factories for inserting dummy data.

Also, don’t forget to define the $fillable property in your model to allow mass assignment of fields.

If you skip this step, Laravel will prevent data from being inserted into the database.

Step 3: Generate a Seeder

To create a new seeder in Laravel 12, use the make:seeder Artisan command:

php artisan make:seeder CategorySeeder

This command generates a new seeder file at database/seeders/CategorySeeder.php. All seeder classes are stored in the database/seeders directory and inherit from the base Seeder class.

Step 4: Write Seeder Logic

Open the generated CategorySeeder.php file and define the data you want to insert in the run() method:

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Category;

class CategorySeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        
        Category::create([
            'name' => 'Laravel',
            'status' => true,
        ]);

        Category::create([
            'name' => 'PHP',
            'status' => false,
        ]);

         


    }
}

This seeder inserts two Category directly into the database.

Step 5: Run the Seeder

Now, let’s run the seeder using the command given below:

php artisan db:seed --class=CategorySeeder

This will insert the sample Category data into your database.

Read Also : Laravel 12 Rollback a Specific Migration

Step 6: Seed Multiple Records Using Factories

If you want to insert multiple category records, use a factory instead.

Run the following command to create a CategoryFactory.php file:

php artisan make:factory CategoryFactory

This command will create a CategoryFactory.php file inside the database/factories directory.

Now, open the CategoryFactory.php file and update it with the following code.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Category>
 */
class CategoryFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
               'name' => fake()->name(),
                'status' => fake()->boolean(), // random true or false
        ];
    }
}

In the CategoryFactory, we use the fake() helper function to generate multiple fake records for testing purposes.

The name field is populated with random names, while the status field is assigned a random boolean value (true or false).

Next, open your CategorySeeder.php file and update the run() method as shown below:

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Category;

class CategorySeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        
        // Category::create([
        //     'name' => 'Laravel',
        //     'status' => true,
        // ]);

        // Category::create([
        //     'name' => 'PHP',
        //     'status' => false,
        // ]);

            Category::factory(10)->create();


    }
}

Finally, run the seeder again using the command:

php artisan db:seed --class=CategorySeeder

This command will generate 10 dummy records for the categories table automatically.

Method 1: Run a Specific Seeder

To run a single seeder directly, use the db:seed command with the –class flag:

php artisan db:seed --class=CategorySeeder

This executes only the CategorySeeder without running any other seeders.

Method 2: Run All Seeders at Once

First, register your seeder in the main DatabaseSeeder file:

<?php

namespace Database\Seeders;


// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $this->call([
           CategorySeeder::class,           
           //UserSeeder::class,           
        ]);

    }
}

Then run all registered seeders with a single command:

php artisan db:seed

This command insert 10 fake users record in user table and 10 category records in category.

Method 3: Run Seeder via Tinker

For quick testing or debugging, you can execute seeders directly in Laravel Tinker:

php artisan tinker

Then run:

(new \Database\Seeders\DatabaseSeeder())->run();

This command will insert 10 fake category records into the categories table feel free to increase or decrease the count as needed.

Or you can simply use the factory to insert dummy records into the database by running the following command:

\App\Models\Category::factory()->count(5)->create();

Important Note

Make sure to use the full model namespace (App\Models\Category::factory(10)->create();) when calling the factory inside Tinker or certain parts of your application. Instead of: Category::factory(10)->create();

Laravel 12 Database Seeder Example
Tinker Seeder Not Found Error

Using only Category::factory() may cause a “Class ‘Category’ not found” error if the model is not imported or the namespace is not recognized. Specifying the full namespace ensures Laravel correctly locates the model.

Method 4: Refresh the Database and Seed in One Command

You can reset your database and seed it again using the migrate:fresh command –seed option:

php artisan migrate:fresh --seed

This will drop all tables, re-run migrations, and then execute all seeders automatically.

To refresh all tables and seed only specific table in a single command, you can use the migrate:fresh command along with the –seed and –seeder options.

This command will drop all the tables, re-run migrations, and then run the specified seeder CategorySeeder to repopulate it.

php artisan migrate:fresh --seed --seeder=CategorySeeder

Conclusion

In this Laravel 12 Database Seeder tutorial, you learned how to create, configure, and run database seeders to populate your tables with dummy or test data.

Seeders are a powerful part of Laravel’s ecosystem that help developers quickly set up and reset their databases during development, testing, or deployment. By combining factories and seeders, you can easily generate realistic sample data without manually entering records.

  • Installed a fresh Laravel project
  • Created a migration and model for the categories table
  • Defined fillable fields and added the HasFactory trait
  • Generated and customized a seeder
  • Used factories to create multiple fake records
  • Learned multiple methods to run and refresh seeders

Using these techniques, you can efficiently manage test data, improve your development workflow, and ensure consistent database states across all environments.