7 March 2024

To add a field that can have a value of null in a CodeIgniter 4 migration, you can specify the field as nullable. The 'null' => true option in the field definition specifies that the field can have a null value.

Source code viewer
  1. namespace App\Database\Migrations;
  2.  
  3. use CodeIgniter\Database\Migration;
  4.  
  5. class Add_nullable_field_migration extends Migration
  6. {
  7. public function up()
  8. {
  9. // Add the new field with nullable option
  10. $fields = [
  11. 'new_field' => [
  12. 'type' => 'VARCHAR',
  13. 'constraint' => 100,
  14. 'null' => true, // This specifies that the field can have a null value
  15. ],
  16. ];
  17.  
  18. $this->forge->addColumn('your_table_name', $fields);
  19. }
  20.  
  21. public function down()
  22. {
  23. // Drop the field if you need to rollback the migration
  24. $this->forge->dropColumn('your_table_name', 'new_field');
  25. }
  26. }
Programming Language: PHP