CodeIgniter 4 Database Seeding From JSON File Tutorial

Reading Time: 7 minutes
7,312 Views

Seeding a database is a crucial aspect of web development, facilitating the initial population of tables with predefined data. In CodeIgniter 4, seeding the database from a JSON file offers a streamlined approach to prefilling tables with structured data.

In this tutorial, we’ll see the comprehensive process of seeding a CodeIgniter 4 database from a JSON file. This functionality empowers developers to efficiently populate tables with predefined data structures stored in a JSON format.

CodeIgniter 4 Database Seeding from CSV File Tutorial, Click here.

In this tutorial we will use JSON file to seed data into database table using CodeIgniter 4.

Read More: CodeIgniter 4 How To Create Fake REST APIs Server

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

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

Either we can do via renaming file as simple as that. Also we can do by terminal command.

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.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.

Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.

Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
  

Now, database successfully connected with the application.

Read More: CodeIgniter How To Send Email with Multiple Attachments

Create Migration

To create table, we will create a migration file. Open project into terminal and run this spark command.

php spark make:migration create_countries_table

It will create a file with name xxx_CreateCountriesTable.php inside /app/Database/Migrations folder.

Open migration file and write this code into it.

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateCountriesTable extends Migration
{
	public function up()
	{
		$this->forge->addField([
			'id' => [
				'type' => 'INT',
				'constraint' => 5,
				'unsigned' => true,
				'auto_increment' => true,
			],
			'sortname' => [
				'type' => 'VARCHAR',
				'constraint' => '10',
				'null' => false
			],
			'name' => [
				'type' => 'VARCHAR',
				'constraint' => '100',
				'null' => false
			],
			'phonecode' => [
				'type' => 'VARCHAR',
				'constraint' => '100',
				'null' => false
			]
		]);
		$this->forge->addPrimaryKey('id');
        $this->forge->createTable('countries');
	}

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

Run Migration

Back to terminal and run this command to migrate it.

php spark migrate

It will create database tables.

Prepare JSON Data File

As we have table countries in which columns as id, name, sortname, phonecode.

We will take a JSON file in which properties of each object will be ID, Sortname, Name & Phonecode. Rest we need data into it.

When you will download the given file it will be in .txt format. Rename file into .json and place this countries-data.json file inside /public/data folder.

Open countries-data.json file, you should see –

Create Model

To create a model, run this spark command into terminal.

php spark make:model Country --suffix

Read More: What are Working Components of CodeIgniter 4?

It will create CountryModel.php inside /app/Models folder.

Open file and write this complete code into it.

<?php

namespace App\Models;

use CodeIgniter\Model;

class CountryModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'countries';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
		"sortname",
		"name",
		"phonecode"
	];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];
}

Create Data Seeder

To create a data seeder, back to terminal and run this spark command into it.

php spark make:seeder Country --suffix

It will create a file with name CountrySeeder.php inside /app/Database/Seeds folder.

Open file and write this complete code into it.

<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use App\Models\CountryModel;

class CountrySeeder extends Seeder
{
	public function run()
	{
		$json = file_get_contents("data/countries-data.json");
		$countries = json_decode($json);

		foreach ($countries->countries as $key => $value) {
			$object = new CountryModel;
			$object->insert([
				"sortname" => $value->sortname,
                "name" => $value->name,
                "phonecode" => $value->phoneCode
			]);
		}
	}
}

Data Seeding

Open project into terminal and run this spark command

php spark db:seed CountrySeeder

It will seed countries data into table. CountrySeeder is the seeder name.

That’s it.

We hope this article helped you to learn about CodeIgniter 4 Database Seeding from JSON File Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more