How To Create Migration In CodeIgniter 4

Using Migrations to create table in database always considered a good practice when you do work in a team. Creating tables manually ( not using migration files) not a good practice as of now, When you do have functionality like migration. If you are working with CodeIgniter usign migrations in CodeIgniter 4 will make you more smarter.

You don’t need to learn SQL to put all this stuff there in form of core PHP. It makes creating tables too easy.

Today we are going to learn migrations in CodeIgniter.

How To Create Migration In CodeIgniter 4

What is migrations in CodeIgniter

Migrations makes easy to create tables in database and which helps to handle tables programmatically and obviously you don’t need to learn about SQL statements to build a table. As I said when you do work with a team then you can easily modify tables and play with the database.

Create table in CodeIgniter using migrations

Now, we are going to create our first table using CodeIgniter migrations.

Overview : We will create a “users” table first and then we will create a “product” table in which we will store products and we will also be using Foreign keys for relation. So, that we can identify the owner of the product. Let’s begin.

Create A Database

Let’s I will create a database called “shopkeeper” and will create both of the tables in this database.

You can create this database table manually or as you wish. After that we will go to Database.php file in Config directory and do configuration.

You just have to fill the hostname,username,password and database for now. And it will work.

'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'shopkeeper',

Create Migration File

After setting up migration you have create the migration file. We will command line for making migration. In CodeIgniter we do use spark.

Create Product table migration file using php spark make:migration create_users_table

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateUsersTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => ['type' => 'INT','usigned'=>true, 'constraint' => 5, 'unsigned' => true, 'auto_increment' => true],
            'parent_id' => ['type' => 'INT'],
            'name' => ['type' => 'VARCHAR', 'constraint' => 200],
            'email' => ['type' => 'VARCHAR', 'constraint' => 200],
            'password' => ['type' => 'VARCHAR', 'constraint' => 200],
            'created_at datetime default current_timestamp',
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('users');
    }

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

Users Table Migration Code Explained

  • In First we have used addField function to create some fields in our Table. That’s all it used for.
  • Secondly, We have used a method called “addKey” to define id as an Primary key.
  • last, We have created the table via createTable() method.

Build register and login in CodeIgniter 4

Migration Using Foreign Key

Foreign Key is a field in one table that refers to the primary key of another table.

The table which has the foreign key called child table and using foreign key prevents the invalid data insert because it needs parent table key.

Create Migration for Product Table to create the Foreign key with Users Table

php spark make:migration create_products_table

After that you have just have to put the product table code in the file. (given below)

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Products extends Migration
{

    public function up()
    {
        $this->forge->addField(
            [
                'id' => [
                    'type' => 'INT',
                    'constraint' => 5,
                    'auto_increment' => TRUE,
                ],
                'user_id' => [
                    'type' => 'INT',
                    'constraint' => 5,
                    'unsigned' => TRUE,
                ],
                'cat_id' => [
                    'type' => 'INT',
                    'constraint' => 5,
                ],
                'name' => [
                    'type' => 'VARCHAR',
                    'constraint' => 350,
                ],
                'price' => [
                    'type' => 'INT',
                    'constraint' => 11,
                ],
                'qty' => [
                    'type' => 'INT',
                    'constraint' => 11,
                ],
                'discription' => [
                    'type' => 'VARCHAR',
                    'constraint' => 350,
                ],
                'image' => [
                    'type' => 'VARCHAR',
                    'constraint' => 255,
                ],
                'created_at datetime default current_timestamp',
            ]
        );
        $this->forge->addForeignKey('id','users','user_id','NULL','NULL');
        $this->forge->addKey('id', true);
        $this->forge->createTable('products');
    }

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

Now, you can create other tables in the same way. If you do have any question please don’t forget to put in the comment box and let’s connect over twitter: Gurpreet kait

Conclusion

Creating table using migration is the best way to make it more flexible. If you are working on your side with a team it becomes easy to modify and discuss over database infrastructure using migration files.

It has some short of Commands to navigate easily.

command line help

  1. Use php spark migrate to migrate the files or tables
  2. Use php spark migrate:rollback to delete all the migrations
  3. Use php spark migrate:refresh to remigrate all the migrations
  4. Use php spark migrate:status to see the migration status.
+----------------------+-------------------+-----------------------+---------+---------------------+-------+
| Namespace            | Version           | Filename              | Group   | Migrated On         | Batch |
+----------------------+-------------------+-----------------------+---------+---------------------+-------+
| App                  | 2022-04-06-234508 | CreateCiSessionsTable | default | 2022-04-06 18:45:14 | 2     |
| CodeIgniter\Settings | 2021-07-04-041948 | CreateSettingsTable   | default | 2022-04-06 01:23:08 | 1     |
| CodeIgniter\Settings | 2021-11-14-143905 | AddContextColumn      | default | 2022-04-06 01:23:08 | 1     |
+----------------------+-------------------+-----------------------+---------+---------------------+-------+

Thank, That's all from Gurpreet kait ❤ Larachamp.