🔥 CodeIgniter Intermediate

What is the Database Forge class in CodeIgniter 4?

Answer

The Database Forge class provides a database-agnostic API for creating, modifying, and dropping database tables — used primarily in migrations. Get Forge: $forge = \Config\Database::forge(). Create a table: $forge->addField(["id" => ["type" => "INT", "constraint" => 11, "unsigned" => true, "auto_increment" => true], "username" => ["type" => "VARCHAR", "constraint" => 100], "created_at" => ["type" => "DATETIME", "null" => true]])->addKey("id", true)->createTable("users"). Add a column: $forge->addColumn("users", ["phone" => ["type" => "VARCHAR", "constraint" => 20, "null" => true]]). Modify column: $forge->modifyColumn(). Drop column: $forge->dropColumn(). Drop table: $forge->dropTable("tablename"). Rename table: $forge->renameTable("old", "new"). Forge generates the appropriate SQL for the active database driver (MySQL, PostgreSQL, SQLite).