If you are working in a development environment, you always need to test your functionality. So for testing, you generally use the test data. You cannot perform the test on real data. Actually, the data may get updated and deleted according to the test cases. So, you can’t use the real data for the testing. It may cause altering the values. You can resolve this by database seeding. Database seeding is a way to insert the sample data into the database table. In CodeIgniter 4, you can create a database seeder using the spark command. The database seeder helps to insert the specified data into the table for testing purposes. There is no limit to data using the seeder. In this post, I will be showing you how you can use Database seeder and faker in Codeigniter 4.
Prerequisites
We wil start from a new installation of CodeIgniter 4. Hence, in order to do that, you will require the below configurations.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create a New Project in CodeIgniter 4
To start create a new project, I will use composer. Just open the terminal and hit the below command.
composer create-project codeigniter4/appstarter ci4-faker
The command will install the CodeIgniter 4 project setup. So just wait till it finishes.
After finishing the installation, let’s create and setup the database for this project.
How to Remove index.php From URL in CodeIgniter 4
Create Database For Database Seeder
We are going to implement the database seeder in CodeIgniter 4. Hence, we will require to have a database and a table. So, firstly, create a database inside the phpMyAdmin.
CREATE DATABASE ci4_seeder;
We have the database ready. Hence, let’s configure the CodeIgniter 4 application to connect it with.
Configure Database in CodeIgniter 4 Project
Please follow the below steps in order to connect the project with a database.
- Firstly, rename the env file to the .env file. You can make a copy of this file even then rename it.
- Secondly, open the .env file and change the environment to development. By default, it is production.
- Lastly, go to the database section inside this file and replace the credentials as showing below.
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = localhost
database.default.database = ci4_seeder
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
Now, the database is connected with our application. In the next step, we’ll create a migration for database seeder.
Upload Multiple Image with Validation in Codeigniter 4
Create a Migration For Database Seeder in CodeIgniter 4
I am not gonna create a table directly inside the database. Instead, I will use migration. Here, I will create a migration file for the users table using the spark command. This will create a users migration file inside the app/Database folder.
php spark make:migration users --table
After creating the file, let’s put the schema for the users table.
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Users extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'auto_increment' => true
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '30'
],
'email' => [
'type' => 'VARCHAR',
'constraint' => '50'
],
'password' => [
'type' => 'VARCHAR',
'constraint' => '20'
],
'phone' => [
'type' => 'VARCHAR',
'constraint' => '15'
],
'address' => [
'type' => 'TEXT'
],
'created_at datetime default current_timestamp',
'updated_at datetime default current_timestamp on update current_timestamp'
]);
$this->forge->addKey('id', true);
$this->forge->createTable('users');
}
public function down()
{
$this->forge->dropTable('users');
}
}
In the above snippet, I have added the schema for the users table. I already explained everything in my previous posts. For more details, you can visit the documentation of CodeIgniter.
Migrate Tables in CodeIgniter 4
After that you need to migrate this migration file. So, that it can dum out the schema with a table inside the database.
php spark migrate
You may check the dumped schema inside the database.
Now, in the next step, we will create a model for the User.
How to Upload Image and File in Codeigniter 4 with Validation
Create a Model For Database Seeder in CodeIgniter 4
In codeIgniter 4, you can associate the table (migration) with a model. Here, you need to specify the table name and the allowed fields. Here, the allowed fields will work as an inputs. That means, whatever values will be inserting in the table, you need to specify those fields inside the allowed fields array.
php spark make:model User
Let’s run the above command. It will generate a User model class inside the app/Models directory. Now, make it look like showing below.
<?php
namespace App\Models;
use CodeIgniter\Model;
class User extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $protectFields = true;
protected $allowedFields = ['name', 'email', 'password', 'phone', 'address'];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
}
Now, you are done at the model, migration and table level. In the next step, you need to create the seeder file.
Create a CRUD Application in CodeIgniter 4 For Beginners
Create Database Seeder in CodeIgniter 4
For seeding the test data in the users table, we will use seeder class. The seeding will insert the records inside the table. Hence, you need to create a seeder related to your table name. So, that you can make a difference if you have multiple tables and seeders. Let’s see how to achieve this.
php spark make:seeder UserSeeder
The above command will generate a seeder class inside the app/Database/Seeds folder.
Once, the seeder file is created, it will look like this.
Inside the UserSeeder.php file, there is a default function that is run(). Here, we will use the Faker Factory class to pass the fake string for each field. The fields will be based on the table that you created inside the database.
Use Faker Factory in CodeIgniter 4
For generating the fake data, we will use the faker factory method. Whatever fields you allowed in the User model, must be passed here. So, for every field, there will be a fake value in the table. So, just make it look like this.
<?php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
use CodeIgniter\I18n\Time;
use App\Models\User;
class UserSeeder extends Seeder
{
public function run()
{
$user = new User;
$faker = \Faker\Factory::create();
for ($i = 0; $i < 10; $i++) {
$user->save(
[
'name' => $faker->name,
'email' => $faker->email,
'password' => password_hash($faker->password, PASSWORD_DEFAULT),
'phone' => $faker->phoneNumber,
'address' => $faker->address,
'created_at' => Time::createFromTimestamp($faker->unixTime()),
'updated_at' => Time::now()
]
);
}
}
}
Let me explain you the above code.
- Inside the run() method, firstly, I initiated the User model. Actually, we are going to insert the fake data inside the users table.
- After that, I have called the create() function of the Factory class.
- Then using the loop, I have passed the array of data inside the User model instance.
- Inside the array, I have specified each fields and related faker property. So, that it can generate a fake value.
Now, that’s it for the faker property. Let’s run the seeder class to get the result.
Form Validation Example in Codeigniter 4 For Beginners
Run Seeder Class in CodeIgniter 4
Before running the seeder class, let me show you the table. Here, I have no records inside the users table.
Now, try hitting the below command in the terminal inside the project folder.
php spark db:seed UserSeeder
On the successful seed, you will have the below result.
Now, let’s take a look at the users table in the database.
SELECT * FROM users;
You may see the result is below. Here, 10 rows are added and data is totally fake generated through the faker class.
You may generate the data according to your use. Here, we used loop and specified the number of iteration of that loop. So, if you may want to insert more records then just increase the counter value of loop.
Bottom Lines
Bingo! we have added the dummy records for the testing purpose of the data. This is possible using the seeder and faker factory method. The seeder allowed to insert the records in the table. While the faker factory method generated the fake records. There are certain defined attributes for fake property. So, I hope, you will love this post.
Leave a Reply