📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials CodeIgniter 4 Database Migrations CI4

Database Migrations CI4

6 min read
Write database migrations with $this->forge to create tables, add indexes, and foreign keys.

Migrations in CI4

// php spark make:migration create_posts_table
namespace AppDatabaseMigrations;
use CodeIgniterDatabaseMigration;

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

    public function down(): void {
        $this->forge->dropTable("posts");
    }
}