Laravel Seeder

What is Seeder in Laravel?

A Seeder in Laravel is used to populate your database with test or default data.

👉 Example:

  • Insert default admin user.
  • Add sample products for testing.
  • Pre-fill country and state lists.

Seeders help you develop and test without manually entering data.


Why Use Seeders?

✅ Quickly fill database with dummy data.

✅ Keep initial data consistent across environments (local, staging, production).

✅ No need to manually insert records via SQL.

✅ Great for testing with sample datasets.


Create a Seeder

Use Artisan command:

php artisan make:seeder UserSeeder

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


Writing Seeder (database/seeders/UserSeeder.php)

Example UserSeeder:

namespace Database\Seeders;

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

class UserSeeder extends Seeder
{
  public function run(): void
  {
    User::create([
      'name' => 'Admin User',
      'email' => 'admin@example.com',
      'password' => bcrypt('password'),
    ]);

    // Create multiple users
    User::factory()->count(10)->create();
  }
}



Running Seeder

php artisan db:seed --class=UserSeeder

DatabaseSeeder File

Laravel uses DatabaseSeeder.php as the main entry point.

Path: database/seeders/DatabaseSeeder.php

You can call multiple seeders inside:

namespace Database\Seeders;

use Illuminate\Database\Seeder;

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


Running Seeder

php artisan db:seed

Combine with Migration

Refresh the database and run seeders:

php artisan migrate:fresh --seed

 

Or with specific seeder:

php artisan migrate:fresh --seeder=UserSeeder

Where to Use Seeders?

  • Development: fill dummy data for testing.
  • Staging: load fixed sample datasets.
  • Production: insert default roles, admin user, settings.

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.