Laravel: Factories and seeders

Laravel: Factories and seeders

October 5, 2019

Factories and Seeders are used for generating fake dummy data in Laravel.

Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database/seeds directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

Laravel docs


Step I: Run following artisan command

Now let’s create a new factory for our posts table. To do this: run the following command:

php artisan make:factory AboutFactory

It will create a new factory at database/factories/AboutFactory.php. Here are the completed contents of the AboutFactory.php file

<?php 
/** @var \Illuminate\Database\Eloquent\Factory $factory */ 
use App\Model; 
use Faker\Generator as Faker; 
$factory->define(\App\About::class, function (Faker $faker) {
    return [        
        'about_data' => $faker->paragraph(2),        
    ];
});

Creating Database Seeds

Database seeds are a way of creating fake data and adding it to your database. It helps you get fake data quickly than creating it manually. Let’s create a seed for about table. To do this run the following commands:

php artisan make:seed AboutSeeder

It will create a new seeder AboutSeeder.php. Here are the completed contents of the AboutFactory.php file

<?php 
      use Illuminate\Database\Seeder;
      class AboutSeeder extends Seeder {
      /** * Run the database seeds. * * @return void */ 
      public function run() { 
      factory(App\About::class, 10)->create();
    }
}
<?php 
          class DatabaseSeeder extends Seeder { 
            /** * Seed the application's database. * * @return void */ 
            public function run() { 
            // $this->call(UsersTableSeeder::class);
            $this->call(AboutSeeder::class);
      }
  }
php artisan db:seed

Above command will run the run method on DatabaseSeeder class. Now our database will contain some fake data generated from model factories. AboutTableSeeder will create 10 users and 10 posts with some dummy title and description.

OUTPUT: