Concept of Migration in CodeIgniter 4 Tutorial

Share this Article
Reading Time: 11 minutes
15 Views

Migration gives the structure scheme of database table. If we have an application in Codeigniter 4 in which we need database tables, better is to create tables using migrations. By creating manual database tables, it will be difficult for those cases when we switch the application from one server to another.

Inside this article we will see the complete concept of migration in codeigniter 4 tutorial. This article is totally from scratch and hope it will be very very interesting.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started for Migration in CodeIgniter 4.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Connect Database To Application

We need to create a database. For database we will use MySQL. We have 2 options available to create database. Either we can use PhpMyAdmin Manual interface Or we can use command to create.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.

To connect application with database. Open .env file and search for Database.

#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Next, we need to create application migration.


Create Migrations

Basic Migration configurations we do inside /app/Config/Migrations.php file. Inside this file, we can set the values of

  • Activate migration feature inside application by using public $enabled = true;
  • Default table name which will be created when we migrate migrations into database, public $table = ‘migrations’; // we can change the name of it.
  • Migration files when created, timestamp value will be attached with the name. So we can change that format too by public $timestampFormat = ‘Y-m-d-His_’;

In CodeIgniter 4, we have php spark commands available to work with migrations. Migrations are the php files which help us to create table scheme and manage that.

Open codeigniter 4 application into terminal and type

$ php spark

We can see into the list of available commands for migration.

When we create migration file, it will be stored inside /app/Database/Migrations folder.

Preparing Migration Files

Type this given command and hit enter.

Syntax

$ php spark make:migration <migration_name>

We need to pass migration name into the command. Let’s say we want to create tables like users and products. So we will create files as add_users and add_products

  • add_users, table: users
  • add_products, table:products
$ php spark make:migration add_users

$ php spark make:migration add_products

The migration file name will be prefixed with a numeric sequence in the date format of YYYY-MM-DD-HHIISS. Please see the CodeIgniter documentation for a more detailed explanation.

Files created for migrations as –

  • 2021-02-09-172057_AddUsers.php
  • 2021-02-09-172108_AddProducts.php

Migration File: 2021-02-09-172057_AddUsers.php

Write the following code into it.

<?php
  
namespace App\Database\Migrations;  
use CodeIgniter\Database\Migration;

class AddUsers extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'INT',
                'constraint' => 5,
                'unsigned' => true,
                'auto_increment' => true,
            ],
            'name' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
                'null' => false
            ],
            'email' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
                'null' => false,
                'unique' => true
            ],
            'updated_at' => [
                'type' => 'datetime',
                'null' => true,
            ],
        'created_at datetime default current_timestamp',
        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('users');
    }

    public function down()
    {
        $this->forge->dropTable('users');
    }
}

Migration File: 2021-02-09-172108_AddProducts.php

Write the following code into it.

<?php

namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;

class AddProducts extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'INT',
                'constraint' => 5,
                'unsigned' => true,
                'auto_increment' => true,
            ],
            'name' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
                'null' => false
            ],
            'description' => [
                'type' => 'TEXT',
                'null' => true
			],
			'amount' => [
                'type' => 'INT',
                'constraint' => 5,
                'unsigned' => true,
			],
			'status' => [
                'type' => 'ENUM',
                'constraint' => ['1', '0'],
                'default' => '1',
            ],
            'updated_at' => [
                'type' => 'datetime',
                'null' => true,
            ],
        'created_at datetime default current_timestamp',
        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('products');
    }

    public function down()
    {
        $this->forge->dropTable('products');
    }
}

Successfully, we have created and updated migration file and their scheme.

Next, we need to migrate into database to create tables. Back to terminal.

$ php spark migrate:status

This command will give migration status means it is migrated to database or not.

Right now, no tables migrated.

Let’s run the command to migrate.

$ php spark migrate

This command will migrate all pending migrations to database. It will basically runs up() method from each migration file.

Database Tables

Open database and you can see, tables will be created.

Also we can see, we have one more table in database. Because we have created only 2, so from where migrations table created ?

migrations table keeps track of migration file. It is by default created by codeigniter 4 application. Table rows always updates when we execute migrate or migrate:rollback. This table behind the scene helps migrate:stauts command to show the status of migration files. If migration entry is in migrations table then its migrated else it will not migrated.


Migration Rollback Concept

This is the feature to rollback the migrations what we have run and created tables. It will drop the created tables from database. It will basically runs down() method from each migration file.

Migration Rollback command

$ php spark migrate:rollback

It will drop the tables from database.


Migrate Refresh Concept

In the last step we have seen the detail of rollback command. So just think for a second. when we again want to migrate tables then we need to execute the command something like this –

Rollback and then create

$ php spark migrate:rollback

$ php spark migrate

We need to execute two different commands for the process of rolling and creating tables.

Now, we have a perfect solution for this i.e Same thing we will do by using a single command.

$ php spark migrate:refresh

Article Summary

Inside this we have discussed the complete details about migrations in CodeIgniter 4. Now you have the concept of each command.

make:migration Creates a new migration file.
migrate:refresh Does a rollback followed by a latest to refresh the current state of the database.
migrate:rollback Runs the "down" method for all migrations in the last batch.
migrate:status Displays a list of all migrations and whether they've been run or not.

We hope this article helped you to learn about Concept of Migration in CodeIgniter 4 Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment