• How To Seed Database Using Faker Library In Laravel

    Here we will create one student table & will insert 1000 dummy records using laravel Faker Factory.It's really interesting. To this we will create a migration file that will create student table along with fake records.
    The columns of table are:
    id
    name
    email
    contact_no
    address
    created_at_updated_at
    Steps to do this task:
    1. Go to cmd & type the following command  

         php artisan make:migration  students
    2. It will create a migration file named as students followed by timestamp as follows.     

         Created Migration: 2018_10_10_125059_students
    3. Then Go to database->migrations in applications & you will find this migration file name.
       Open that file & edit the up() as belows.
        public function up()
        {
            Schema::create('students', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->string('email')->unique();
                $table->string('contact_number');
                $table->string('address');
                $table->timestamps();       
            });
            $faker = Faker\Factory::create();
            $limit = 1000;
            for ($i = 0; $i < $limit; $i++) {
                DB::table('students')->insert([ //,
                    'name' => $faker->name,
                    'email' => $faker->unique()->email,
                    'contact_number' => $faker->phoneNumber,
                    'address' => $faker->address,
                ]);
            }
        }
    Note: $limit: no of records to insert in table
              $faker = Faker\Factory::create(); creates an instance of Faker factory
              $faker->name creates a faker name
              $faker->unique()->email creates a fake unique email address,
              $faker->phoneNumber creates a fake Phone Number
              $faker->address creates a fake address
    4. Save the file & go to cmd & type the following command    
         php artisan migrate    
    it will show the output as follows in cmd.
    Migrating: 2018_10_10_125217_create_students_table
    Migrated:  2018_10_10_125217_create_students_table

    5. Then Go to localhost/phpmyadmin. Check your database. One table named students is created with dummy 1000 records.
    The structure of table :


    The dummy records of students table: 







  • You might also like

    1 comment: