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 thedatabase/seeders directory. A DatabaseSeeder class is provided by default.
Creating a seeder
Generate a new seeder class with themake:seeder Artisan command.
database/seeders/UserSeeder.php.
Implementing a seeder
Write your data insertion logic in therun() method. You can use the DB facade or Eloquent models to insert data.
Using the DB facade
Using Eloquent models
Mass assignment protection is automatically disabled during seeding. You can insert data without worrying about
$fillable or $guarded settings.Combining with model factories
When you need large amounts of test data, combining with model factories is convenient. Factories let you generate random dummy data in bulk.Using DatabaseSeeder
DatabaseSeeder is the entry point that manages multiple seeders together. Specify seeders to run with the call() method.
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
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.
Running together with migrations
Add the--seed option to the migrate:fresh command to recreate all tables and run seeding in one shot.
--seeder option.
Running in production
When you try to run seeding in production, a confirmation prompt is shown. To run without confirmation, use the--force flag.
Suppressing model events
If you want to prevent model events (creating, created, and so on) from firing during seeding, use the WithoutModelEvents trait.
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.Next steps
Eloquent introduction
Learn how to retrieve and manipulate seeded data with the Eloquent ORM.