Seeders

Seeders

Normally after running “php artisan migrate:fresh“, your database tables are recreated but empty. Manually inserting data each time is tedious, so seeders automate this process.

Seeders are classes located in the database/seeders directory. The default DatabaseSeeder class is your entry point to run multiple seeders.

To run seeders, use:

Bash
php artisan db:seed

Creating and Running Seeders

If you encounter errors like missing columns, ensure your seeders and factories match your database schema.

You can combine migration and seeding in one command:

Bash
php artisan migrate:fresh --seed

This drops all tables, runs migrations, and seeds the database in one go.

Using Factories in Seeders

Seeders often use factories to generate large amounts of fake data quickly:

PHP
\App\Models\Job::factory(200)->create();

This creates 200 job records using the factory definition.

It’s easy to call a factory in a seeder. Here’s how:

PHP
Job::factory(200)->create();

Splitting Seeders for Flexibility

You can create multiple seeder classes for different parts of your database:

Bash
php artisan make:seeder JobSeeder

This makes a new seeder class called “JobSeeder”.

This allows running seeders individually or in groups, useful for testing or partial data refreshes.

In your DatabaseSeeder, call other seeders:

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

Tags: