Seeder or seedbeds in CodeIgniter 4 to generate test data

- Andrés Cruz

En español
Seeder or seedbeds in CodeIgniter 4 to generate test data

Seeders are the mechanism we have to generate test data in a simple way; they are strongly linked to the migrations in CodeIgniter 4, since the problem with the migrations is that when we rollback, we lose all the test data... but with the seeders we can get this data back in a very short time; instead of creating it manually.

We can generate the seeders or seedbeds via the command line; following the recommended schema, we should create one per entity or at least one; but we must avoid handling multiple entities from a single file, but you could, for example, if you see it necessary, generate two seedbeds to generate different users, with different roles.

Generate the seeder using spark

The command is:

php spark db:seed UserSeeder

Where UserSeeder is the name you want to give to the file and class

We have a function called run, which is what we use to generate the test data, either individually or in a cycle based on some condition; in our case, we generate about 6 test users

public function run()
    {
        $userModel = new UserModel();
        for ($i = 0; $i < 5; $i++) {
            $userModel->insert([
                'username' => 'user' . $i,
                'email' => "user$i@gmail.com",
                'password' => '12345'
            ]);
        }
    }

Then, to run the seeder:

php spark make:seeder UserSeeder

And voila, when we review the database, we will see our generated users.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.