Run Specific Seeder in Laravel 12 The Complete Guide

Hey there, Laravel developers! If you’ve ever needed to populate your database with test data in Laravel 12, you’ve likely used seeders. But what if you only want to run a specific seeder instead of all of them? I’ve been there, and I’m excited to share a beginner-friendly guide on running specific seeders in Laravel 12.

This task is crucial for testing, development, and even production setups. With practical code snippets and clear steps, you’ll master seeding specific data efficiently.

Why Run Specific Seeders in Laravel 12?

Seeders in Laravel allow you to populate your database with predefined or fake data, which is essential for:

  1. Testing: Create realistic data for unit or integration tests.
  2. Development: Set up sample data for local environments.
  3. Production: Initialize specific tables with required data.
  4. Debugging: Reproduce issues by seeding targeted data.

Running all seeders can be overkill, especially if you only need to populate one table (e.g., users). Laravel 12’s seeding system, built on Eloquent and Query Builder, makes it easy to target specific seeders.

Step-by-Step Guide: Run Specific Seeders in Laravel 12

Run Specific Seeder in Laravel 12 The Complete Guide

This guide covers how to create, configure, and run specific seeders in Laravel 12. We’ll use a UsersTableSeeder as an example and explore multiple methods to execute it selectively.

Prerequisites

- Laravel 12 installed.

- Database configured (e.g., MySQL, PostgreSQL).

- Terminal access (Command Prompt, PowerShell, or WSL2).

Step 1: Set Up a Laravel 12 Project

Create a New Project:

composer create-project --prefer-dist laravel/laravel laravel-seeder-example
cd laravel-seeder-example

Configure Database:
Update env:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_seeder
DB_USERNAME=root
DB_PASSWORD=

Run Migrations:

php artisan migrate

This creates the default users table.

Step 2: Create a Specific Seeder

Generate a Seeder:

php artisan make:seeder UsersTableSeeder

This creates database/seeders/UsersTableSeeder.php.

Define Seeder Logic:
Edit database/seeders/UsersTableSeeder.php:

<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class UsersTableSeeder extends Seeder
{
    public function run()
    {
        User::create([
            'name' => 'John Doe',
            'email' => '[email protected]',
            'password' => Hash::make('password123'),
        ]);

        User::create([
            'name' => 'Jane Smith',
            'email' => '[email protected]',
            'password' => Hash::make('password123'),
        ]);
    }
}

Update DatabaseSeeder:
By default, DatabaseSeeder runs all seeders. For flexibility, leave it empty or call specific seeders conditionally:

<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        // Leave empty or call seeders conditionally
    }
}

 

Step 3: Run a Specific Seeder

Laravel provides multiple ways to run a specific seeder. Here are the most effective methods:

Method 1: Using db:seed with --class

Run the Seeder:

php artisan db:seed --class=UsersTableSeeder

Verify Data:
Check the users table in your database or use Tinker:

php artisan tinker
User::all();

Output:

[
    ['id' => 1, 'name' => 'John Doe', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'Jane Smith', 'email' => '[email protected]']
]

When to Use:

- Ideal for running a single seeder in development or production.

- Simple and direct.

Method 2: Calling Seeder from DatabaseSeeder

Update DatabaseSeeder:
Modify database/seeders/DatabaseSeeder.php:

public function run()
{
    $this->call(UsersTableSeeder::class);
}

Run All Seeders:

php artisan db:seed

This only runs UsersTableSeeder since it’s the only one called.

When to Use:

- Useful when you want to control seeders programmatically.

- Good for temporary or conditional seeding.

Method 3: Using Artisan Command Directly

Run Seeder via Artisan:

php artisan db:seed --class=Database\Seeders\UsersTableSeeder

Specify the full namespace if the seeder is in a custom directory.

When to Use:

- Necessary if seeders are in non-standard namespaces or directories.

Method 4: Using Tinker to Run Seeder

Open Tinker:

php artisan tinker

Run Seeder:

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

When to Use:

- Great for quick testing or debugging.

- Avoid in production due to manual execution.

Step 4: Using Factories with Specific Seeders

For dynamic data, combine seeders with factories.

Create a Factory:

php artisan make:factory UserFactory

Edit database/factories/UserFactory.php:

<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'password' => bcrypt('password123'),
        ];
    }
}

Update Seeder:
Modify UsersTableSeeder:

public function run()
{
    \App\Models\User::factory()->count(10)->create();
}

Run Specific Seeder:

php artisan db:seed --class=UsersTableSeeder

Output:

Creates 10 random users in the users table.

When to Use:

- Ideal for generating large datasets or realistic test data.

Step 5: Run Specific Seeder in Production

Backup Database:

mysqldump -u root -p laravel_seeder > backup.sql

Run Seeder:

php artisan db:seed --class=UsersTableSeeder --force

The --force flag bypasses confirmation prompts.

Verify:
Check the users table or query:

php artisan tinker
User::count();

 

Step 6: Troubleshooting Common Issues

Seeder Not Found:

Ensure the seeder class exists in database/seeders.

Use the correct namespace: php artisan db:seed --class=Database\Seeders\UsersTableSeeder.

Duplicate Data:

Truncate the table before seeding:

public function run()
{
    User::truncate();
    User::factory()->count(10)->create();
}

Database Connection Errors:

Verify .env settings and run php artisan migrate.

Best Practices for Laravel 12 Specific Seeders

Organize Seeders: Group seeders by table or feature (e.g., UsersTableSeeder, PostsTableSeeder).

Use Factories: Combine seeders with factories for dynamic data.

Avoid Hardcoding: Use environment variables or configs for sensitive data:

User::create(['email' => config('app.admin_email')]);

Test Seeders: Run seeders in a staging environment first.

Integrate with Authentication: Seed users for testing Laravel 12 authentication (e.g., Laravel Passport, see your previous article).

Version Control: Commit seeders to Git for reproducibility.

Real-World Example: Seeding for Authentication Testing

To test Laravel 12 API authentication, seed users with specific roles:

Update Seeder:

public function run()
{
    User::create([
        'name' => 'Admin User',
        'email' => '[email protected]',
        'password' => Hash::make('password123'),
        'role' => 'admin',
    ]);

    User::factory()->count(5)->create(['role' => 'user']);
}

Run Seeder:

php artisan db:seed --class=UsersTableSeeder

Test with API:
Use your Laravel 12 API authentication setup (e.g., Passport) to log in as [email protected] and verify roles.

Conclusion

Running specific seeders in Laravel 12 is a powerful way to manage database data for testing, development, or production. This guide covered multiple methods—using db:seed --class, DatabaseSeeder, Tinker, and factories—to execute targeted seeders efficiently.

Frequently Asked Questions(FAQs)

Q1: How do I run a specific seeder in Laravel 12?
A: Use php artisan db:seed --class=UsersTableSeeder to run a single seeder.

Q2: Can I use factories with specific seeders?
A: Yes, combine factories in your seeder: User::factory()->count(10)->create().

Q3: Why does my seeder create duplicate data?
A: Truncate the table before seeding: User::truncate() in the seeder’s run method.

Q4: What if I get “‘composer’ is not recognized” during setup?
A: Add C:\Users\<YourUsername>\AppData\Roaming\Composer\vendor\bin to your system PATH.

Q5: How do I run a specific seeder in production?
A: Use php artisan db:seed --class=UsersTableSeeder --force and back up your database first.


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS