Getting Started with CodeIgniter 4 Database Seeding: A Beginner Guide

Database seeding is a way of populating a database with test data that can be used for initial testing to explore the various functions of your application instead of having to create test users one by one every time you want to test something new.

In CodeIgniter 4 database seeding feature is available.

This post guides you through the creation of database seeding and running single or multiple seeding files in CodeIgniter 4.

Getting Started with CodeIgniter 4 Database Seeding: A Beginner Guide


Table of Content

  1. Update Database Configuration
  2. Create 2 Tables using Migration
  3. Create 2 Models using Migration
  4. Create Seeding files
  5. Insert data using Seeder
  6. Run seeders
  7. Output
  8. Conclusion

1. Update Database configuration

  • Open .env file which is available at the project root.

NOTE – If dot (.) not added at the start then rename the file to .env.

  • Remove # from start of database.default.hostname, database.default.database, database.default.username, database.default.password, and database.default.DBDriver.
  • Update the configuration and save it.
database.default.hostname = 127.0.0.1
database.default.database = testdb
database.default.username = root
database.default.password = 
database.default.DBDriver = MySQLi

2. Create 2 Tables using Migration

Creating 2 tables –

  • Users
  • Products

Users table

  • Create a table users using migration.
php spark migrate:create create_users_table
  • Now, navigate to app/Database/Migrations/ folder from the project root.
  • Find a PHP file that ends with CreateUsersTable and open it.
  • Define the table structure in the up() method.
  • Using the down() method delete users table which calls when undoing migration.
<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateUsersTable extends Migration {

    public function up() {
        $this->forge->addField([
            'id' => [
                'type' => 'INT',
                'constraint' => 5,
                'unsigned' => true,
                'auto_increment' => true,
            ],
            'name' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
            ],
            'username' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
            ],
            'email' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
            ],
            'age' => [
                'type' => 'INT',
                'constraint' => '2',
            ],
            'status' => [
                'type' => 'INT',
                'constraint' => '2',
            ],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('users');
    }

    public function down() {
        $this->forge->dropTable('users');
    }
}

Products table 

  • Create products table.
php spark migrate:create create_products_table
  • Now, navigate to app/Database/Migrations/ folder and open PHP file that ends with CreateProductsTable.
  • Define the table structure in the up() method.
  • Using the down() method delete products table.
<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateProductsTable extends Migration {

     public function up() {
         $this->forge->addField([
            'id' => [
                'type' => 'INT',
                'constraint' => 5,
                'unsigned' => true,
                'auto_increment' => true,
            ],
            'fullname' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
            ],
            'description' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
            ],
            'quantity' => [
                'type' => 'INT',
                'constraint' => '2',
            ],
            'status' => [
                'type' => 'INT',
                'constraint' => '2',
            ],
         ]);
         $this->forge->addKey('id', true);
         $this->forge->createTable('products');
     }

     public function down() {
         $this->forge->dropTable('products');
     }
}
  • Run the migration –
php spark migrate

3. Create 2 Models using Migration

Generate Two Models:

  • Users and
  • Products

Users Model

To create the Users model, follow these steps:

1. Run the following command:

php spark make:model Users

2. Navigate to the app/Models/Users.php file.
3. Inside the $allowedFields array, define the field names that can be modified during both insertion and updating – ['name', 'username', 'email', 'age', 'status'].

<?php

namespace App\Models;

use CodeIgniter\Model;

class Users extends Model
{
     protected $DBGroup = 'default';
     protected $table = 'users';
     protected $primaryKey = 'id';
     protected $useAutoIncrement = true;
     protected $insertID = 0;
     protected $returnType = 'array';
     protected $useSoftDeletes = false;
     protected $protectFields = true;
     protected $allowedFields = ['name','username','email','age','status'];

     // Dates
     protected $useTimestamps = false;
     protected $dateFormat = 'datetime';
     protected $createdField = 'created_at';
     protected $updatedField = 'updated_at';
     protected $deletedField = 'deleted_at';

     // Validation
     protected $validationRules = [];
     protected $validationMessages = [];
     protected $skipValidation = false;
     protected $cleanValidationRules = true;

     // Callbacks
     protected $allowCallbacks = true;
     protected $beforeInsert = [];
     protected $afterInsert = [];
     protected $beforeUpdate = [];
     protected $afterUpdate = [];
     protected $beforeFind = [];
     protected $afterFind = [];
     protected $beforeDelete = [];
     protected $afterDelete = [];
}

Products Model

For the Products Model, use the following procedure:
1. Generate the Products Model with the command:

php spark make:model Products

2. Find and open the file app/Models/Products.php.
3. In the $allowedFields array, specify the field names that are eligible for modification during both the insertion and updating processes – ['name', 'description', 'quantity', 'status'].

<?php

namespace App\Models;

use CodeIgniter\Model;

class Products extends Model
{
     protected $DBGroup = 'default';
     protected $table = 'products';
     protected $primaryKey = 'id';
     protected $useAutoIncrement = true;
     protected $insertID = 0;
     protected $returnType = 'array';
     protected $useSoftDeletes = false;
     protected $protectFields = true;
     protected $allowedFields = ['name','description','quantity','status'];

     // Dates
     protected $useTimestamps = false;
     protected $dateFormat = 'datetime';
     protected $createdField = 'created_at';
     protected $updatedField = 'updated_at';
     protected $deletedField = 'deleted_at';

     // Validation
     protected $validationRules = [];
     protected $validationMessages = [];
     protected $skipValidation = false;
     protected $cleanValidationRules = true;

     // Callbacks
     protected $allowCallbacks = true;
     protected $beforeInsert = [];
     protected $afterInsert = [];
     protected $beforeUpdate = [];
     protected $afterUpdate = [];
     protected $beforeFind = [];
     protected $afterFind = [];
     protected $beforeDelete = [];
     protected $afterDelete = [];
}

4. Create Seeding files

Creating 3 seeding files –

  • UserSeeder
  • ProductSeeder
  • ManageSeeder – Using this run multiple seeders.

Syntax –

php spark make:seeder [Seeder-name] --suffix

UserSeeder

php spark make:seeder user --suffix

ProductSeeder

php spark make:seeder product --suffix

ManageSeeder

php spark make:seeder manage --suffix

Created files are stored in app/Database/Seeds/ folder.


5. Insert data using Seeder

UserSeeder

  • Open app/Database/Seeds/UserSeeder.php file.
  • Include App\Models\Users Model to insert data in the users table.
  • In the run() method write script –
    • Load text helper to generate a random string and pick random value from available values – 0,1.
    • Insert a record with predefined values and insert 5 records with random values.
<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use App\Models\Users;

class UserSeeder extends Seeder
{
    public function run()
    {
         // Helper to generate random values
         helper('text');

         // Insert Record with Fix values
         $user = new Users();

         $insertdata['name'] = 'Yogesh';
         $insertdata['username'] = 'yssyogesh';
         $insertdata['email'] = 'yogesh@makitweb.com';
         $insertdata['age'] = 29;
         $insertdata['status'] = 1;

         $user->insert($insertdata);

         // Insert 5 Records with Dynamic values 
         for($num=0;$num<5;$num++){
              $user = new Users();

              $insertdata['name'] = random_string('alpha');
              $insertdata['username'] = random_string('alpha');
              $insertdata['email'] = random_string('alpha').'@makitweb.com';
              $insertdata['age'] = rand(25,40);
              $insertdata['status'] = alternator(0,1);

              $user->insert($insertdata);
         }
    }
}

ProductSeeder

  • Open app/Database/Seeds/ProductSeeder.php file.
  • Include App\Models\Products Model.
  • In the run() method write script –
    • Load text helper.
    • Insert 5 records with random values.
<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use App\Models\Products;

class ProductSeeder extends Seeder
{
     public function run()
     {
          // Helper to generate random values
          helper('text');

          // Insert 5 Records with Dynamic values 
          for($num=0;$num<5;$num++){
              $product = new Products();

              $insertdata['name'] = random_string('alpha');
              $insertdata['description'] = random_string('alpha',30);
              $insertdata['quantity'] = rand(10,200);
              $insertdata['status'] = alternator(0,1);

              $product->insert($insertdata);
          }
     }
}

ManageSeeder

  • Open app/Database/Seeds/ManageSeeder.php file.
  • In the run() method specify seeder names that need to execute using $this->call().
  • I specified UserSeeder and ProductSeeder.

NOTE – Only mention those seeder file names that you want to execute from this seeder.

<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;

class ManageSeeder extends Seeder
{
     public function run()
     {
          $this->call('UserSeeder');
          $this->call('ProductSeeder');
     }
}

6. Run seeders

Run single Seeder

php spark db:seed UserSeeder
php spark db:seed ProductSeeder

Execute the above commands one by one.


Run multiple Seeders

Command is the same as above but specify the seeder name from where you are calling all seeders using $this->call(). In the example, I created ManageSeeder to call other seeders –

php spark db:seed ManageSeeder

After executing the command new records will be inserted into the database.


7. Output

View Output


8. Conclusion

Using database seeding you can speed up the development and bug-fixing process. If you want to run multiple seeders using single command then create a seeding file and mention the seeders name using $this->call().

If you found this tutorial helpful then don't forget to share.

Leave a Comment