agyanadda@gmail.com

CodeIgniter 4 Seeders

Database and Models 1 min read Updated Dec 3, 2026 Topic 12 of 30

Seeders put data into your tables — sample data while developing, or required starting data such as categories and an admin user.

Create a seeder

php spark make:seeder CategorySeeder creates app/Database/Seeds/CategorySeeder.php. Write your inserts in the run() method using $this->db.

Run it

php spark db:seed CategorySeeder

A main seeder

Create DatabaseSeeder and call others from it with $this->call('CategorySeeder');. Then one command seeds everything.

Fake data

For realistic test data, use Faker (composer require fakerphp/faker --dev): $faker = \Faker\Factory::create('en_IN'); gives names, emails, sentences and more. CodeIgniter also has a Fabricator class that uses Faker with your models.

Tips

  • Use insertBatch() to insert many rows in one query
  • Hash passwords: password_hash('secret', PASSWORD_DEFAULT)
  • On a live server, seed only required data, and avoid creating duplicates

Example

Example — Categories and an admin user PHP
<?php
namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->db->table('users')->insert([
            'name'     => 'Admin',
            'email'    => 'admin@example.com',
            'password' => password_hash('admin123', PASSWORD_DEFAULT),
        ]);

        $this->db->table('categories')->insertBatch([
            ['name' => 'PHP',        'slug' => 'php'],
            ['name' => 'JavaScript', 'slug' => 'javascript'],
            ['name' => 'MySQL',      'slug' => 'mysql'],
        ]);

        $this->call('PostSeeder');   // run another seeder
    }
}

// Terminal:
// php spark db:seed DatabaseSeeder

Creates one admin user with a hashed password, three categories in a single query, then runs PostSeeder.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which command runs a seeder?

Exercise 2 True / False

insertBatch() inserts many rows in one query.

Exercise 3 Fill in the Blank

Run another seeder from inside a seeder with $this->___('PostSeeder')

Frequently Asked Questions

Always store it hashed with password_hash(). For a live site, create the admin with a strong temporary password and change it after the first login.