Generate dummy data in Laravel using Model Factory


Mar 16, 2018    Janaki Mahapatra, Laravel

Here are the steps needed to create dummy data
  • Lets create a model called Sample with migration file, using php artisan command
    php artisan make:model Sample -m
  • Run the migration by
    php artisan migrate
  • Generate a factory
    php artisan make:factory SampleFactory --model=Sample
    The new factory will be placed in your database/factories directory.
  • Open the SampleFactory class and add
    $factory->define(App\Sample::class, function (Faker $faker) {
        return [
            'name' => $faker->name,
            'email' => $faker->unique()->safeEmail,
            'phone' => $faker->phoneNumber,
            'description' => $faker->text(200)
        ];
    });
    
  • Create a seeder by using artisan command
    php artisan make:seeder SamplesTableSeeder
  • Open the SamplesTableSeeder class file
    use Illuminate\Database\Seeder;
    
    class SamplesTableSeeder extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run()
        {
            factory(App\Sample::class,100)->create();
        }
    }
    /*
    Where 
    App\Sample => is the model class
    100 => number of rows 
    */
    
  • Once the seeder is ready, we need to regenerate Composer's autoloader using the dump-autoload command:
    composer dump-autoload
    then run either
    php artisan db:seed // to run all the seeder classes
    
    or
    php artisan db:seed --class=SamplesTableSeeder // for a single class
    
Now you can see the records in samples table.