CodeIgniter 4 - Seeder and Faker

Posted by Ridwan Fadilah on Jul 29, 2020 - 08:06 pm

Seeder and Faker

Learn about how to create a seeder and generate dummy data by using faker in CodeIgniter 4. Database seeding and faker usage example.

After you learn about CodeIgniter 4 Database Migrations in the previous tutorial, now, I'll show you how to use seeder and faker to seeds the database in CodeIgniter 4.

Check out the previous tutorial about CodeIgniter 4 - Database Migrations.

Database seeding is a simple way to add data into your database. It is especially useful during development where you need to populate the database with sample data that you can develop against, but it is not limited to that. Source: codeigniter.com

What is Seeder? Seeder is a method used for inserting data automatically into a database table that have created.

What is Faker? Faker is dummy data that will insert into a database table by using the seeder.

In simple word, seeder and faker is used to fill the database table.

Table of Contents

Database Seeding (CodeIgniter Seeder)

Seeder

Database seeds are simple classes that must have a run() method, and extend CodeIgniterDatabaseSeeder.

Seeds can contain static data that you don't want to include in a migration like countries, geo-coding tables, and more.

You can't run the seeder before you create the seeds files. That's the first step to seeds your database.

Create a Seeds Files

As you know, you can use the CLI to create a migration. However, to make a seeder, you not to be able to use the CLI. You need to create it by hand manually. But, don't worry, CodeIgniter 4 is still allows you to use the CLI to run it.

Check out the previous tutorial about CodeIgniter 4 - Database Migrations.

How to create a seeder? To make a seeder in CodeIgniter 4, just create a new file and named as do you want (example: PeopleSeeder.php) on your App/Migrations/Seeds directory.

Seeds Directory

Seeds File:



<?php

namespace App\Database\Seeds;

use \CodeIgniter\I18n\Time;

class PeopleSeeder extends \CodeIgniter\Database\Seeder
{
  public function run()
  {
    $data = [
      'name'        => 'Ridwan Fadilah',
      'address'     => '8090 Banana Street, 12',
      'created_at'  => Time::now(),
      'updated_at'  => Time::now()
    ];

    // Simple Queries
    $this->db->query(
      "INSERT INTO peoples (name, address, created_at, updated_at) VALUES(:name:, :address:, :created_at:, :updated_at:)",
      $data
    );

    // Using Query Builder
    $this->db->table('peoples')->insert($data);
  }
}


After the seeder created, choose one of the queries you want to use. You can use the simple query or using the query builder for seeding into your database table.

Using Simple Queries

Before running the seeder, be sure you have run the SQL and app server.



<?php

namespace App\Database\Seeds;

use \CodeIgniter\I18n\Time;

class PeopleSeeder extends \CodeIgniter\Database\Seeder
{
  public function run()
  {
    $data = [
      'name'        => 'Ridwan Fadilah',
      'address'     => '8090 Banana Street, 12',
      'created_at'  => Time::now(),
      'updated_at'  => Time::now()
    ];

    // Simple Queries
    $this->db->query(
      "INSERT INTO peoples (name, address, created_at, updated_at) VALUES(:name:, :address:, :created_at:, :updated_at:)",
      $data
    );
  }
}

Now, to run seeder use the command line to seed data as part of the Migrations CLI tools.

Command:


> php spark db:seed PeopleSeeder

You don't need to add the PHP extension.

You will get a 'seeded' message if the seeding operation is successful:

Data Seeded

Now you can try to check your database table to make sure the result of the seeding process:

Database Table Seeded

Using Query Builder

Using the query builder is more simple than if you use the simple queries. You don't need to modify the query like before (adding name, address, and more into the query manually). You only need to use the insert with the $data array as the parameter.



<?php

namespace App\Database\Seeds;

use \CodeIgniter\I18n\Time;

class PeopleSeeder extends \CodeIgniter\Database\Seeder
{
  public function run()
  {
    $data = [
      'name'        => 'Jhon Due',
      'address'     => '8090 Banana Street, 12',
      'created_at'  => Time::now(),
      'updated_at'  => Time::now()
    ];

    // Using Query Builder
    $this->db->table('peoples')->insert($data);
  }
}


You will get the same result if you don't have a problem with your code, SQL, or the app server:

Database Table Result with Query Builder

Multiple Data Seeding

Multiple data seeding is allowed by CodeIgniter 4. You can add more than one data by putting the data inside the multi dimensional-array.

Example:



<?php

namespace App\Database\Seeds;

use \CodeIgniter\I18n\Time;

class PeopleSeeder extends \CodeIgniter\Database\Seeder
{
  public function run()
  {
    $data = [
      [
        'name'        => 'Andy',
        'address'     => '8733 Apple Street, 10',
        'created_at'  => Time::now(),
        'updated_at'  => Time::now()
      ],
      [
        'name'        => 'Buddy',
        'address'     => '643 Banana Street, 135',
        'created_at'  => Time::now(),
        'updated_at'  => Time::now()
      ],
      [
        'name'        => 'Anie',
        'address'     => '112 Lemon Street, 121',
        'created_at'  => Time::now(),
        'updated_at'  => Time::now()
      ]
    ];

    // Using Query Builder
    $this->db->table('peoples')->insert($data);
  }
}


However, you can't use the insert() for multiple data seeding. You will get an error like this:

Error Data Seeding

The solution to that is by using the insertBatch().

Example:



<?php

namespace App\Database\Seeds;

use \CodeIgniter\I18n\Time;

class PeopleSeeder extends \CodeIgniter\Database\Seeder
{
  public function run()
  {
    $data = [
      [
        'name'        => 'Andy',
        'address'     => '8733 Apple Street, 10',
        'created_at'  => Time::now(),
        'updated_at'  => Time::now()
      ],
      [
        'name'        => 'Buddy',
        'address'     => '643 Banana Street, 135',
        'created_at'  => Time::now(),
        'updated_at'  => Time::now()
      ],
      [
        'name'        => 'Anie',
        'address'     => '112 Lemon Street, 121',
        'created_at'  => Time::now(),
        'updated_at'  => Time::now()
      ]
    ];

    // Using Query Builder
    $this->db->table('peoples')->insertBatch($data);
  }
}


Now, the data will be inserted with no problem:

Multiple Data Inserted or Seeded

Faker (Dummy Data)

Faker

Now, how to insert a hundred or thousand dummy data? You can do that by using the faker and looping. By using faker, it's possible to seed hundred or thousand data into your database table.

Faker is not a built-in function in CodeIgniter 4. Faker is an external library that could connect and used with CodeIgniter 4. So, you need to install it first.

Faker Installation

Before you install a faker, be sure you have composer installed on your computer. If you haven't to install the composer, see the Installation Guide - How to Install Composer PHP Dependency Manager on Windows Computer.

Run this command to install faker:


composer require fzaninotto/faker

Wait until it finishes.

Faker Installation

Create Fake Data

This part is the next step after the faker installation.

With faker, you can insert any data like name, address, time, date, and more. See faker documentation for more usage.

You need to create fake data that would be seeding into your database. You also need to add the faker namespace on your seeds file.


$faker = \Faker\Factory::create();

If faker and looping are used, you can use the query builder with the insert() method.

Example:


<?php

namespace App\Database\Seeds;

use \CodeIgniter\I18n\Time;

class PeopleSeeder extends \CodeIgniter\Database\Seeder
{
  public function run()
  {
    $faker = \Faker\Factory::create('id_ID');

    for ($i = 0; $i < 150; $i++) {
      $data = [
        'name'        => $faker->name,
        'address'     => $faker->address,
        'created_at'  => Time::createFromTimestamp($faker->unixTime()),
        'updated_at'  => Time::now()
      ];

      // Using Query Builder
      $this->db->table('peoples')->insert($data);
    }
  }
}

The ('id_ID') parameter is the localization. That defines Indonesian. See the faker documentation for more localization.

The $faker->name is used to generate a random name.

The $faker->address is used to generate a random address.

The Time::createFromTimestamp($faker->unixTime()) is used to convert UNIX time to string.

Seeding Fake Data

After you create fake data, you can seed your database now.

Just run your seeder with the same command to start the seeding process.

Command:


> php spark db:seed PeopleSeeder

If you don't have a problem with your code, SQL, or the app server, your database will be seeded like this:

Database Seeded with Faker

Okay, that's the tutorial about CodeIgniter 4 Database Seeder and Faker. If you want to learn more about CodeIgniter, see the related article below.

You can find another tutorial on our YouTube Channel.

Thanks for reading this article.


Related Articles