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:
php artisan db:seedCreating 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:
php artisan migrate:fresh --seedThis 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:
\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:
Job::factory(200)->create();Splitting Seeders for Flexibility
You can create multiple seeder classes for different parts of your database:
php artisan make:seeder JobSeederThis 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:
public function run()
{
$this->call([
UserSeeder::class,
JobSeeder::class,
]);
}