Database migration means moving your data from one platform to another.
Migrations come in handy when you are working in a team or a group of developers. These are a convenient way of altering the database in an organized and structured manner.
We have to keep versions of our database changes similar to versioning of files. This means we can go back and forth easily to a specific version of database changes.
The first framework that came up with this idea was Laravel and now CodeIgniter also allows us to set up migrations which is really good for us.
Setting Up Migrations in CI
In order to enable migrations:
- Open application/config/migration.php file and set the value for
- Create a folder called migrations in application/config/ folder and that’s it.
In the migrations folder, we can create our database changes. Let’s say we want to create a new users table. To do so, create a file called 001_add_users.php in migrations folder and paste this code in it:
class Migration_Add_user extends CI_Migration
public function up()
'id' => array(
'type' => 'INT',
'constraint' => 5,
'unsigned' => true,
'auto_increment' => true
'name' => array(
'type' => 'VARCHAR',
'constraint' => '100',
'email' => array(
'type' => 'TEXT',
'null' => true,
public function down()
In the above code:
- It has two methods
- It uses
dbforgeobject to build up queries in the way of Object-Oriented Programming.
- The migration files should be prefixed with three digits like
002_migration_file_second.phpand so on
So that’s how a migration class should look like.
up() method is called by system whenever you need to update the database and
down() method is used to revert that change that was done by the
up() method. For example, if in the
up() method you create a new table then in the
down() method you should specify the code to remove that table. Similarly if in the
up() method you add a new field to some table then in the
down() method you should specify code that deletes that field. So both of these methods are opposite to each other. In each migration, you always have to specify the code for both.
We created our migration, now we need to run it. So, we will create a controller called
class migrate extends CI_Controller
public function index()
// load migration library
echo 'Error' . $this->migration->error_string();
echo 'Migrations ran successfully!'
In the above example, we used
$this->migration->current() method to go to the current migration version that is set in
Database migrations are really awesome and very helpful!