CodeIgniter 4 Migrations Complete Tutorial [Latest] πŸ’‘

Reading Time: 8 minutes
8 Views

Managing database changes in any application should be structured, repeatable, and easy to track. In CodeIgniter 4, this is made simple with Migrations. Migrations let us version-control the database schema so that structure updates can be easily applied, reverted, or modified across development, staging, and production environments.

This tutorial covers everything about CodeIgniter 4 Migrations:

  • How migrations work
  • Creating migrations
  • Running and rolling back migrations
  • Checking migration history

Let’s get started.

πŸ“Œ What is a Migration?

A migration is a PHP class that defines changes to the database structure like creating tables, modifying columns, or deleting them. CodeIgniter 4’s migration system keeps track of which migrations have run and in what order.

Migration files stored inside:

app/Database/Migrations/

πŸ“Œ Creating a Migration

Let’s create a migration to set up a products table.

Command:

php spark make:migration CreateProductsTable

πŸ‘‰ Explanation: This command generates a new migration file in app/Database/Migrations/ with a timestamp prefix to ensure the correct order of execution.

Example Output:

Created file: APPPATH/Database/Migrations/2025-06-25-063045_CreateProductsTable.php

Read More: REST APIs in CodeIgniter 4 with JWT Authentication

>> Basic class structure

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateProductsTable extends Migration
{
    public function up()
    {
        // Add fields and create table code here
    }

    public function down()
    {
        // Drop table code here
    }
}

πŸ“Œ Writing Migration Code

We can add code to create and define the table structure inside the up() method.

public function up()
{
    $this->forge->addField([
        'id'          => ['type' => 'INT', 'auto_increment' => true],
        'name'        => ['type' => 'VARCHAR', 'constraint' => '100'],
        'price'       => ['type' => 'DECIMAL', 'constraint' => '10,2'],
        'created_at'  => ['type' => 'DATETIME', 'null' => true],
    ]);
    $this->forge->addKey('id', true);
    $this->forge->createTable('products');
}

Rollback (down) method:

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

πŸ‘‰ Explanation: The up() method builds the table, while down() defines how to reverse that change if rolled back.

πŸ“Œ Running Migrations

Once the migration files are created and the database changes are defined within the up() and down() methods, it’s time to apply those migrations to the database.

In CodeIgniter 4, applying migrations is a breeze thanks to the Spark CLI. This ensures that all migrations are run in the correct order based on their timestamped filenames.

Command:

php spark migrate

πŸ‘‰ Explanation: This command scans the app/Database/Migrations/ directory for any new migration files that haven’t been applied yet. It then executes the up() method for each of those files, applying the defined changes to the database.

Sample Output:

Running all new migrations...
Done migrations.

πŸ“Œ Running a Specific Migration

To run a particular migration file:

Command:

php spark migrate --name CreateProductsTable

πŸ‘‰ Explanation: Executes only the migration file matching the given name.

πŸ“Œ Rollback Migrations

Sometimes, after applying migrations, it becomes necessary to reverse changes β€” whether due to mistakes, testing needs, or database restructuring.

CodeIgniter 4 makes this easy with the rollback feature, which safely undoes the most recent batch of migrations by executing the down() method of each migration file involved.

Command (single step rollback):

php spark migrate:rollback

πŸ‘‰ Explanation: This command rolls back the last executed batch of migrations. CodeIgniter internally maintains a migrations table that records which migrations ran and in which batch. Running this command triggers the down() method in each migration of the latest batch, effectively undoing those database changes.

Command (rollback multiple batches):

php spark migrate:rollback --batch 2

πŸ‘‰ Explanation: This command rolls back the last two batches sequentially. Useful when several groups of migrations need to be undone in one go.

Command (rollback all migrations):

php spark migrate:reset

πŸ‘‰ Explanation: This command reverts all applied migrations, calling the down() method for each migration file from the latest to the earliest.

πŸ“Œ Refresh Migrations (Reset and Re-run)

During development, there might be situations where a fresh database schema setup is needed β€” for example, after tweaking several migrations or while testing seeding data. CodeIgniter 4 makes this easy with the migrate:refresh command.

Command:

php spark migrate:refresh

πŸ‘‰ Explanation: This command performs two actions in sequence:

  • Rolls back all applied migrations by calling their down() methods.
  • Re-applies all migrations by running their up() methods in the correct order.

It’s a quick way to reset and rebuild the database schema without manually running rollback and migrate commands separately.

Command with seeding:

php spark migrate:refresh --seed

πŸ‘‰ Explanation: Along with refreshing the database structure, this command also runs the database seeders defined in your application.

πŸ“Œ Check Migration Status

To keep track of which migrations have already been applied and which are still pending, CodeIgniter 4 offers the migrate:status command.

Command:

php spark migrate:status

πŸ‘‰ Explanation: This command displays a table listing:

  • Migration filename
  • Batch number (to which group of migrations it belongs)
  • Status (whether it has been run or not)

It’s an essential tool for developers to quickly view migration progress, identify pending migrations, and verify the current database schema state.

πŸ“Œ Conclusion

CodeIgniter 4’s migration system ensures safe, consistent, and manageable database structure updates. By integrating these migration commands into the workflow, database schema changes stay organized and are easily reversible.

With just a few Spark CLI commands, it becomes effortless to create tables, modify fields, rollback mistakes, and track migration history without manually tinkering with the database.