Migrations and Seeders

CodeIgniter 137 views Dec 22, 2025 2 min read

Migrations and Seeders in CodeIgniter (CodeIgniter 4)

Migrations and Seeders help you manage database structure and data programmatically, making your project easy to version, share, and deploy.


1. Migrations

What Is a Migration?

  • A PHP file that defines database schema changes

  • Version control for your database

  • Allows easy rollback and updates


Migration Location

app/Database/Migrations/

Creating a Migration

php spark make:migration CreateUsersTable

Migration Example

namespace App\Database\Migrations; use CodeIgniter\Database\Migration; class CreateUsersTable extends Migration { public function up() { $this->forge->addField([ 'id' => [ 'type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true, ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => 100, ], 'email' => [ 'type' => 'VARCHAR', 'constraint' => 150, ], 'created_at DATETIME DEFAULT CURRENT_TIMESTAMP', ]); $this->forge->addKey('id', true); $this->forge->createTable('users'); } public function down() { $this->forge->dropTable('users'); } }

Running Migrations

php spark migrate

Rollback:

php spark migrate:rollback

Migration Status

php spark migrate:status

2. Seeders

What Is a Seeder?

  • Inserts sample or default data into tables

  • Useful for testing and development


Seeder Location

app/Database/Seeds/

Creating a Seeder

php spark make:seeder UserSeeder

Seeder Example

namespace App\Database\Seeds; use CodeIgniter\Database\Seeder; class UserSeeder extends Seeder { public function run() { $data = [ [ 'name' => 'Admin', 'email' => 'admin@example.com' ], [ 'name' => 'User', 'email' => 'user@example.com' ], ]; $this->db->table('users')->insertBatch($data); } }

Running Seeders

php spark db:seed UserSeeder

Running Multiple Seeders

$this->call('UserSeeder'); $this->call('PostSeeder');

3. Enable Migrations

In .env:

database.default.DBPrefix =

In app/Config/Migrations.php:

public $enabled = true;

4. Best Practices

✅ Use migrations for all schema changes
✅ Never edit DB manually in production
✅ Seed only non-sensitive data
❌ Don’t use seeders for production user data


5. Migrations vs Seeders

FeatureMigrationsSeeders
PurposeDB structureDB data
VersionedYesNo
RollbackYesNo

Summary

  • Migrations manage database schema

  • Seeders populate initial/sample data

  • Essential for teamwork and deployment

  • Fully supported via Spark CLI

Some advanced sections are available for Registered Members
Share this Post
🚀 Want to Test Your Knowledge?

Take quizzes related to this topic and see where you stand!

Start Quiz Now
Back to Tutorials