Laravel Factory and Seeder

Follow the steps below to seed a database with sample data:

  • Make factory associated with a table:
    php artisan make:factory tablenameFactory -m modelname
    • in the created factory class, use faker to generate the fake data corresponding to each column you want to seed in the table.  For example, the following sets data to two columns named company and email:
    • Foreign key constraints: for example, a company refers to a product code in a separate product table:

      This will create a product entry for reference sake.

  • Add Seeder
    php artisan make:seeder subjectsTableSeeder

    Note: subjectsTableSeeder follows the naming convention of (plural form of table subject)+TableSeeder

    • In the run method of subjectsTableSeeder, add call to the corresponding factory class. For example:

      In this example, three instances of fake users will be populated

  • Modify super class databaseSeeder to run individual seeders.  In the run method of databaseSeeder add the following:
  • Run the following command to seed data:
    php artisan db:seed
  • Some additional useful commands:
    • To delete all data from the database:
      php artisan migrate:fresh
    • To reseed after deleting all data from the database:
      php artisan migrate:fresh --seed
    • Reset composer if a file name has changed:
      composer dump -autoload