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:
      'company'=>faker->company;
      'email'=>faker->unique()->safeemail;
    • Foreign key constraints: for example, a company refers to a product code in a separate product table:
      'product_code'=>factory(product::class)->create();

      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:
      factory(\App\User::class,3)->create();

      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:
    $this->call(subjectsTableSeeder::class);
  • 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