agyanadda@gmail.com

CodeIgniter 4 Migrations

Database and Models 1 min read Updated Dec 3, 2026 Topic 11 of 30

Migrations are PHP files that create or change tables. Everyone on the team (and the live server) runs the same files, so databases stay in sync.

Create a migration

php spark make:migration CreatePostsTable creates a file in app/Database/Migrations with:

  • up() — create or change tables
  • down() — undo the change

Define columns with Forge

Use $this->forge->addField([...]) with an array per column: type, constraint (length), unsigned, auto_increment, null, default.

  • $this->forge->addKey('id', true) — primary key
  • $this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE')
  • $this->forge->createTable('posts')
  • In down(): $this->forge->dropTable('posts')

Commands

  • php spark migrate — run new migrations
  • php spark migrate:rollback — undo the last batch
  • php spark migrate:refresh — roll back everything and run again (deletes data)
  • php spark migrate:status — what has run

To change an existing table later, create a new migration (for example AddSlugToPosts) using $this->forge->addColumn().

Example

Example — Posts table migration PHP
<?php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreatePostsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id'         => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
            'user_id'    => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
            'title'      => ['type' => 'VARCHAR', 'constraint' => 255],
            'slug'       => ['type' => 'VARCHAR', 'constraint' => 255],
            'body'       => ['type' => 'TEXT'],
            'status'     => ['type' => 'VARCHAR', 'constraint' => 20, 'default' => 'draft'],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'updated_at' => ['type' => 'DATETIME', 'null' => true],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey('slug');
        $this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
        $this->forge->createTable('posts');
    }

    public function down()
    {
        $this->forge->dropTable('posts');
    }
}

php spark migrate creates the posts table with a primary key, a unique slug and a foreign key to users. migrate:rollback drops it again.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which command runs pending migrations?

Exercise 2 True / False

migrate:refresh is safe to run on a live database with real data.

Exercise 3 Fill in the Blank

Create the table with $this->forge->___('posts')

Frequently Asked Questions

No. Create a new migration that changes the table (addColumn, modifyColumn, dropColumn). Edit old migrations only on your own computer before anyone else has run them.