Migrations and Seeders

πŸ“˜ CodeIgniter πŸ‘ 37 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

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
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes