CodeIgniter 4 Database Seeding From CSV File Tutorial

Share this Article
Reading Time: 7 minutes
336 Views

Inside this article we will see the concept of database seeding in CodeIgniter 4 using csv file. CodeIgniter 4 database seeding from csv file is technique to dump test data into tables in bulk.

This tutorial will be super easy to understand and it’s steps are easier to implement in your code as well. Database seeding is the process in which we feed test data to tables. We can insert data either using Faker library, manual data or means of some more data sources like CSV, JSON.

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

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

Learn More –

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.


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.


Turn Development Mode On

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

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.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.

Let’s connect with the application.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

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

Now, database successfully connected with application.


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 2021-08-12-041623_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 CSV File

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

We will take a CSV file in which the columns 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 .csv and place this countries.csv file inside /public/data folder.

Open countries.csv file, you should see –


Create Model

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

$ php spark make:model Country --suffix

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 CountrySeeder.php 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()
	{
		$csvFile = fopen("data/countries.csv", "r");
        // It will automatically read file from /public/data folder.

        $firstline = true;
        while (($data = fgetcsv($csvFile, 2000, ",")) !== FALSE) {
            if (!$firstline) {
				$object = new CountryModel;
				$object->insert([
					"sortname" => $data['1'],
					"name" => $data['2'],
					"phonecode" => $data['3']
				]);
            }
            $firstline = false;
        }

        fclose($csvFile);
	}
}

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.

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

Buy Me a Coffee

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