CodeIgniter 4 migrations and seeders: manage the database

Create and run CodeIgniter 4 migrations and seeders with correct Spark commands, valid PHP examples and safeguards for data.

CodeIgniter 4 migrations and seeders: manage the database

Create and run CodeIgniter 4 migrations and seeders with correct Spark commands, valid PHP examples and safeguards for data.

Versioned schema

Migrations describe incremental schema changes. Files in app/Database/Migrations have a timestamp prefix and a unique class: up() applies the change and down() reverses it. The migrations table tracks what has run. Check the connection and back up data before changing an existing database.

Generate a migration

Run php spark make:migration CreateNewsTable from the project directory. This generates a skeleton; complete up() and down() as shown. Forge creates the news table with a primary key and three fields. The down() method drops the table and its data.

<?php
// app/Database/Migrations/YYYY-MM-DD-HHMMSS_CreateNewsTable.php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateNewsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'INT', 'constraint' => 11,
                'unsigned' => true, 'auto_increment' => true,
            ],
            'title' => ['type' => 'VARCHAR', 'constraint' => 255],
            'slug' => ['type' => 'VARCHAR', 'constraint' => 255],
            'text' => ['type' => 'TEXT'],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('news');
    }

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

Run and inspect

php spark migrate applies pending migrations in the App namespace; php spark migrate:status displays their status. Use php spark migrate --all when migrations across all configured namespaces are intended. Check the selected database group and namespace. Do not rely on a nonexistent migrate:latest step.

Rollback and refresh

php spark migrate:rollback reverts migrations to the initial state; -b chooses a batch. php spark migrate:refresh rolls back and then reruns all migrations. Both can destroy data. Limit them to test databases unless you have checked the effects, backups and a recovery plan.

Sample seeder

A seeder extends CodeIgniter\Database\Seeder and implements run(). Generate its skeleton with php spark make:seeder NewsSeeder, then add fictional rows as in the example. Execute it with php spark db:seed NewsSeeder. Do not assume an unnamed db:seed command runs all files. Running this simple example repeatedly adds duplicates unless you add uniqueness or an existence check.

<?php
// app/Database/Seeds/NewsSeeder.php
namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;

class NewsSeeder extends Seeder
{
    public function run()
    {
        $this->db->table('news')->insertBatch([
            ['title' => 'Sample one', 'slug' => 'sample-one', 'text' => 'Demo text'],
            ['title' => 'Sample two', 'slug' => 'sample-two', 'text' => 'Demo text'],
        ]);
    }
}

Working as a team

Commit migrations and seeders; create a new migration instead of editing one already applied elsewhere. Reference data needs an update and repeatability strategy. Keep personal data out of sample seeders. Test application and rollback in staging before running planned migrations in production.

Sources

CodeIgniter documentation: https://codeigniter4.github.io/CodeIgniter4/dbmgmt/migration.html ; seeders: https://codeigniter4.github.io/CodeIgniter4/dbmgmt/seeds.html .

Share

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0