Why Seeders are important
While a project is in development phase, developers have to drop and re-create all database tables in development life-cycle.
php artisan migrate:refresh
Laravel provides command line utility as mentioned above to drop and recreate tables but it removes stored data from tables. Inserting testing data manually is tedious, repetitive and time consuming.
How to create Seeder Classes
To automate this process, Laravel includes simple method of seeding database table using seeder class.
Laravel provides nice command to generate Seeder class –
php artisan make:seeder Seeders/UsersTableSeeder
This will generate UsersTableSeeder file under Seeders folder. It contains only “run” method and being called when db:seed command is run from command prompt. We can write code to insert single/multiple data into DB table.
How to run Seeders
php artisan db:seed
This command is useful to run all seeders at one go. This is useful first time we create DB and wants to insert test data in multiple tables.
php artisan db:seed --class=UsersTableSeeder
Laravel also provides an option to run particular seeder. To do so, we need to provide seeder class name in “–class” option.
php artisan migrate:refresh --seed
Laravel also provide command to run all seeders after refreshing database. Rather than firing 2 separate commands we can use this one to fill db with test data immediately after refreshing db