Why Seed Your Database?
Seeding lets you populate your database with default or test data. It's great for development environments, demos, and running tests against consistent datasets.
The DatabaseSeeder Class
Every Laravel project ships with a DatabaseSeeder class in the database/seeders directory. This is the entry point for all your seeding logic.
class DatabaseSeeder extends Seeder
{
public function run()
{
User::factory(10)->create();
}
}
The run method executes when you trigger the seeder from the command line.
Running the Seeder
Use the artisan command to seed your database. This runs the DatabaseSeeder class and all seeders it calls.
php artisan db:seed
You can also seed a specific seeder class directly.
php artisan db:seed --class=PostSeeder
To refresh your database and re-seed in one step, use migrate:fresh --seed.
Creating Custom Seeders
For more control, generate a dedicated seeder for each table. Keep your seeding logic organized and modular.
php artisan make:seeder PostSeeder
Inside the seeder, use the insert method or factories to add records.
class PostSeeder extends Seeder
{
public function run()
{
Post::factory(20)->create();
}
}
Call this seeder from DatabaseSeeder to keep everything in one place.
Using Factories and Raw Data
You can mix factory-generated data with raw values. This is handy when some fields need specific formats or relationships.
public function run()
{
User::factory()
->count(5)
->create()
->each(function ($user) {
$user->posts()->saveMany(
Post::factory(3)->make()
);
});
}
Seeders keep your development environment consistent and make onboarding new team members effortless.