Database Seeding
Relevant source files
The following files were used as context for generating this wiki page:Database seeders provide a simple way to add initial or test data into your database. This is particularly useful for setting up an application for the first time, or for ensuring a consistent database state for automated testing. All seeder classes are stored in the app/Database/Seeds/ directory and are simple classes that must extend CodeIgniter\Database\Seeder.
Within a seeder class, the primary logic is contained within the run() method. This method is where you can use the Query Builder, Models, or any other method to insert data into your database tables. The framework provides tools to generate and run these seeders, making database population a straightforward and repeatable process.
Sources: source/dbmgmt/seeds.rst:3-11
Creating a Seeder
You can create a new seeder file using the make:seeder Spark command. This command will generate a new seeder class file in the app/Database/Seeds/ directory.
php spark make:seeder UserSeeder
This command creates a file named app/Database/Seeds/UserSeeder.php with the following basic structure:
<?php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
class UserSeeder extends Seeder
{
public function run()
{
//
}
}
The autoloader knows to find the seeder file because of the PSR-4 namespace mapping defined in app/Config/Autoload.php, which maps the App namespace to the app directory.
Sources: source/dbmgmt/seeds.rst:13-20, source/cli/database_commands.rst, source/general/configuration.rst:100-105
Seeder Class Structure
All seeders must extend the CodeIgniter\Database\Seeder base class. This provides access to helpful properties and methods for database interaction.
The following diagram shows the inheritance structure for a custom seeder.
This diagram illustrates how a user-defined seeder like UserSeeder inherits from the base CodeIgniter\Database\Seeder class.
Key components available within a seeder class include:
$this->db: The database connection instance, allowing you to perform any database operations.$this->forge: The Database Forge instance, used for schema manipulation if needed.run(): The abstract method that must be implemented in your seeder. It is executed when the seeder is run.call(): A method to execute other seeders.
Sources: source/dbmgmt/seeds.rst:22-30
Running Seeders
Seeders can be executed via the command line using Spark, or called directly from your code.
Using the CLI
The primary way to run seeders is with the db:seed Spark command.
| Command | Description |
|---|---|
php spark db:seed | Executes the main Database\Seeds\DatabaseSeeder class. |
php spark db:seed UserSeeder | Executes the specified seeder class (UserSeeder). |
When run without specifying a seeder name, the command looks for and runs the DatabaseSeeder class. This class can be used as a master seeder to call other seeders in a specific order.
Sources: source/cli/database_commands.rst, source/dbmgmt/seeds.rst:64-70
The following flowchart shows the execution path of the db:seed command.
This diagram shows the logic flow when the db:seed command is executed, either with a specific seeder name or defaulting to DatabaseSeeder.
Calling Programmatically
You can also run seeders from within your application code, such as in a controller or during a custom installation script. This is done by calling the seeder() method from the database configuration.
$seeder = \Config\Database::seeder();
$seeder->call('UserSeeder');
This approach provides flexibility for triggering database seeding outside of the CLI.
Sources: source/dbmgmt/seeds.rst:72-76
Organizing Seeders
For applications with many seeders, it is best practice to create a main DatabaseSeeder class that orchestrates the execution of all other seeders. This allows you to control the seeding order and manage all seeders from a single location.
The $this->call() method is used inside the run() method of DatabaseSeeder to execute another seeder.
// app/Database/Seeds/DatabaseSeeder.php
<?php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call('UserSeeder');
$this->call('ProductSeeder');
$this->call('OrderSeeder');
}
}
When you run php spark db:seed, it will execute DatabaseSeeder, which in turn will execute UserSeeder, ProductSeeder, and OrderSeeder in sequence.
Sources: source/dbmgmt/seeds.rst:54-62
The sequence diagram below illustrates how DatabaseSeeder calls other seeders.
This diagram shows the chain of calls initiated by running the main DatabaseSeeder.
Inserting Data
Inside the run() method, you can use the Query Builder to insert data. This is the most common approach for populating tables.
Single Row Insertion
Use the insert() method to add a single row of data.
// In app/Database/Seeds/UserSeeder.php
public function run()
{
$data = [
'username' => 'darth',
'email' => 'darth@theempire.com',
];
// Simple Queries
$this->db->query('INSERT INTO users (username, email) VALUES(:username:, :email:)', $data);
// Using Query Builder
$this->db->table('users')->insert($data);
}
Sources: source/dbmgmt/seeds.rst:32-43
Multiple Row Insertion
For inserting multiple records at once, insertBatch() is more efficient.
// In app/Database/Seeds/UserSeeder.php
public function run()
{
$data = [
[
'username' => 'darth',
'email' => 'darth@theempire.com',
],
[
'username' => 'luke',
'email' => 'luke@therebellion.com',
],
];
$this->db->table('users')->insertBatch($data);
}
Sources: source/dbmgmt/seeds.rst:45-52, source/database/query_builder.rst:430-445
Seeding in Tests
Database seeding is essential for creating a predictable database state for feature tests. The RefreshDatabase trait can be used in your test classes to automatically migrate and seed the database before each test.
To specify which seeder to run for a test, set the $seed property in your test class.
<?php
namespace App\Controllers;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
use CodeIgniter\Test\FeatureTestTrait;
class ExampleTest extends CIUnitTestCase
{
use DatabaseTestTrait;
use FeatureTestTrait;
// The name of the seeder class to run
protected $seed = 'TestUserSeeder';
// ... your tests
}
When this test class is run, the framework will first run all migrations and then execute the TestUserSeeder class, ensuring the database is in a known state.
Sources: source/testing/database.rst:10-12, 114-124
Summary
Database Seeding in CodeIgniter 4 is a powerful feature for populating your database with data for development, initial setup, or testing. By creating simple seeder classes and using the db:seed Spark command, you can easily manage and version-control your database's initial state. The ability to organize seeders and integrate them into the testing workflow with the RefreshDatabase trait makes it an indispensable tool for robust application development.
Sources: source/dbmgmt/seeds.rst, source/testing/database.rst