Seeders
A seeder is a class that fills tables with data: test posts for development or required records such as a list of categories. With it a database that is empty after migrations gets content in a second, so pages can be checked against it. Seeders live in the app/Database/Seeds folder.
Creating a seeder
php spark make:seeder PostSeederThe command creates the file app/Database/Seeds/PostSeeder.php with an empty run() method. Add one record to it:
// app/Database/Seeds/PostSeeder.php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
class PostSeeder extends Seeder
{
public function run()
{
$this->db->table('posts')->insert([
'title' => 'First post',
'body' => 'The text of the first post.',
'status' => 1,
'created_at' => date('Y-m-d H:i:s'),
]);
}
}The $this->db property is the database connection. The table('posts') method chooses the table, insert() adds a row.
Running
php spark db:seed PostSeederThe terminal reports that the seeder has run, and a record appears in the posts table. Every run adds the rows again — a seeder does not check whether they already exist.
Many records
Several rows are easier to build in a loop and insert with one query:
public function run()
{
$posts = [];
for ($i = 1; $i <= 20; $i++) {
$posts[] = [
'title' => "Post #$i",
'body' => 'The text of the post.',
'status' => $i % 3 === 0 ? 0 : 1,
'created_at' => date('Y-m-d H:i:s'),
];
}
$this->db->table('posts')->insertBatch($posts);
}insertBatch() takes an array of rows. The table gets twenty posts, every third one with status 0, that is a draft.
Several seeders
When there are more tables, a main seeder calls the others in the right order:
// app/Database/Seeds/DatabaseSeeder.php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call('UserSeeder');
$this->call('PostSeeder');
}
}Now one command fills the whole database: php spark db:seed DatabaseSeeder.
Starting from a clean database
During development the database is often rebuilt from scratch:
php spark migrate:refresh
php spark db:seed DatabaseSeederThe first command drops and recreates the tables, the second fills them.
Common mistake
A seeder does not clear the table: run it twice and there are twice as many records, and with unique columns the second run ends with an error. Before filling again, rebuild the tables with migrate:refresh or clear the table at the start of run() with $this->db->table('posts')->truncate(). Test seeders are never run on the live server.