> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Database seeding

> Learn how to populate your database with sample data for development and testing using Laravel's seeding feature.

## What is seeding

Seeding is the mechanism for populating your database with sample or initial data.

When setting up a development environment or running automated tests, you need data to already exist. Manually entering data each time is tedious, so seeders let you bundle it up into a repeatable form.

Seeder classes are stored in the `database/seeders` directory. A `DatabaseSeeder` class is provided by default.

```mermaid theme={null}
flowchart TD
    A["php artisan db:seed"] --> B["DatabaseSeeder::run()"]
    B --> C["UserSeeder::run()"]
    B --> D["PostSeeder::run()"]
    C --> E["Insert data into users table"]
    D --> F["Insert data into posts table"]
```

## Creating a seeder

Generate a new seeder class with the `make:seeder` Artisan command.

```shell theme={null}
php artisan make:seeder UserSeeder
```

The generated file is placed at `database/seeders/UserSeeder.php`.

```php theme={null}
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class UserSeeder extends Seeder
{
    /**
     * Run the seeder.
     */
    public function run(): void
    {
        // Write your data insertion logic here
    }
}
```

## Implementing a seeder

Write your data insertion logic in the `run()` method. You can use the DB facade or Eloquent models to insert data.

### Using the DB facade

```php theme={null}
<?php

namespace Database\Seeders;

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

class UserSeeder extends Seeder
{
    public function run(): void
    {
        DB::table('users')->insert([
            [
                'name' => 'Taro Yamada',
                'email' => 'taro@example.com',
                'password' => Hash::make('password'),
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'name' => 'Hanako Suzuki',
                'email' => 'hanako@example.com',
                'password' => Hash::make('password'),
                'created_at' => now(),
                'updated_at' => now(),
            ],
        ]);
    }
}
```

### Using Eloquent models

```php theme={null}
use App\Models\User;
use Illuminate\Support\Facades\Hash;

public function run(): void
{
    User::create([
        'name' => 'Administrator',
        'email' => 'admin@example.com',
        'password' => Hash::make('password'),
    ]);
}
```

<Info>
  Mass assignment protection is automatically disabled during seeding. You can insert data without worrying about `$fillable` or `$guarded` settings.
</Info>

## Combining with model factories

When you need large amounts of test data, combining with [model factories](/en/eloquent) is convenient. Factories let you generate random dummy data in bulk.

```php theme={null}
use App\Models\User;
use App\Models\Post;

public function run(): void
{
    // Create 10 users
    User::factory(10)->create();

    // Create 3 posts per user
    User::factory(5)
        ->hasPosts(3)
        ->create();
}
```

<Tip>
  For detailed usage of factories, see the Eloquent factories documentation.
</Tip>

## Using DatabaseSeeder

`DatabaseSeeder` is the entry point that manages multiple seeders together. Specify seeders to run with the `call()` method.

```php theme={null}
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

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

Seeders run in the order you pass them to `call()`. If there are foreign key constraints, order them so the referenced tables are seeded first (for example, `users` → `posts`).

## Running seeders

### Running all seeders

```shell theme={null}
php artisan db:seed
```

`DatabaseSeeder` is invoked, and it runs the seeders you specified via `call()` in order.

### Running only a specific seeder

Use the `--class` option to specify the seeder class to run.

```shell theme={null}
php artisan db:seed --class=UserSeeder
```

## Running together with migrations

Add the `--seed` option to the `migrate:fresh` command to recreate all tables and run seeding in one shot.

```shell theme={null}
php artisan migrate:fresh --seed
```

To run only a specific seeder, use the `--seeder` option.

```shell theme={null}
php artisan migrate:fresh --seed --seeder=UserSeeder
```

<Warning>
  `migrate:fresh` drops all tables and recreates them. All existing data is lost, so do not use it in production.
</Warning>

## Running in production

When you try to run seeding in production, a confirmation prompt is shown. To run without confirmation, use the `--force` flag.

```shell theme={null}
php artisan db:seed --force
```

<Warning>
  Seeding in production can lead to data being overwritten or lost. Always take a backup before running.
</Warning>

## Suppressing model events

If you want to prevent model events (`creating`, `created`, and so on) from firing during seeding, use the `WithoutModelEvents` trait.

```php theme={null}
<?php

namespace Database\Seeders;

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

class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;

    public function run(): void
    {
        $this->call([
            UserSeeder::class,
        ]);
    }
}
```

It also applies to child seeders invoked via `call()`.

## Practical example: seeders for a blog app

Here's an example of setting up initial data for a blog app with users and posts.

```php theme={null}
// database/seeders/UserSeeder.php
class UserSeeder extends Seeder
{
    public function run(): void
    {
        User::factory(10)->create();
    }
}

// database/seeders/PostSeeder.php
class PostSeeder extends Seeder
{
    public function run(): void
    {
        // Create 2 to 5 posts per user
        User::all()->each(function ($user) {
            Post::factory(rand(2, 5))->create([
                'user_id' => $user->id,
            ]);
        });
    }
}

// database/seeders/DatabaseSeeder.php
class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $this->call([
            UserSeeder::class,
            PostSeeder::class, // Run after users
        ]);
    }
}
```

Execution steps:

```shell theme={null}
php artisan migrate:fresh --seed
```

## Next steps

<Card title="Eloquent introduction" icon="database" href="/en/eloquent">
  Learn how to retrieve and manipulate seeded data with the Eloquent ORM.
</Card>


## Related topics

- [Database migrations](/en/migrations.md)
- [Database configuration](/en/database.md)
- [Eloquent Factories](/en/eloquent-factories.md)
- [Database Testing](/en/database-testing.md)
- [Advanced Testing with Pest](/en/advanced/testing-pest.md)
