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 tablesdown()— 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 migrationsphp spark migrate:rollback— undo the last batchphp 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
<?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.