Database Seeding

Database seeding is a simple way to add data into your database. It is especially useful during development whereyou need to populate the database with sample data that you can develop against, but it is not limited to that.Seeds can contain static data that you don’t want to include in a migration, like countries, or geo-coding tables,event or setting information, and more.

Database seeds are simple classes that must have a run() method, and extend CodeIgniterDatabaseSeeder.Within the run() the class can create any form of data that it needs to. It has access to the databaseconnection and the forge through $this->db and $this->forge, respectively. Seed files must bestored within the app/Database/Seeds directory. The name of the file must match the name of the class.

  1. <?php namespace App\Database\Seeds;
  2.  
  3. class SimpleSeeder extends \CodeIgniter\Database\Seeder
  4. {
  5. public function run()
  6. {
  7. $data = [
  8. 'username' => 'darth',
  9. 'email' => 'darth@theempire.com'
  10. ];
  11.  
  12. // Simple Queries
  13. $this->db->query("INSERT INTO users (username, email) VALUES(:username:, :email:)",
  14. $data
  15. );
  16.  
  17. // Using Query Builder
  18. $this->db->table('users')->insert($data);
  19. }
  20. }

Nesting Seeders

Seeders can call other seeders, with the call() method. This allows you to easily organize a central seeder,but organize the tasks into separate seeder files:

  1. <?php namespace App\Database\Seeds;
  2.  
  3. class TestSeeder extends \CodeIgniter\Database\Seeder
  4. {
  5. public function run()
  6. {
  7. $this->call('UserSeeder');
  8. $this->call('CountrySeeder');
  9. $this->call('JobSeeder');
  10. }
  11. }

You can also use a fully-qualified class name in the call() method, allowing you to keep your seedersanywhere the autoloader can find them. This is great for more modular code bases:

  1. public function run()
  2. {
  3. $this->call('UserSeeder');
  4. $this->call('My\Database\Seeds\CountrySeeder');
  5. }

Using Seeders

You can grab a copy of the main seeder through the database config class:

  1. $seeder = \Config\Database::seeder();
  2. $seeder->call('TestSeeder');

Command Line Seeding

You can also seed data from the command line, as part of the Migrations CLI tools, if you don’t want to createa dedicated controller:

  1. > php spark db:seed TestSeeder