Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Seeds

An empty table is inconvenient for development: the list page has nothing to show. A seed is a class that adds ready-made records to a table. It is run with a command, so all developers get the same data set.

Where they live

Seeds are in the config/Seeds folder. They are handled by the same Migrations plugin as migrations.

Creating

bin/cake bake seed Articles

The command creates the file config/Seeds/ArticlesSeed.php with an empty data array.

The seed file

Fill the array with two articles:

// config/Seeds/ArticlesSeed.php
use Migrations\AbstractSeed;
 
class ArticlesSeed extends AbstractSeed
{
    public function run(): void
    {
        $data = [
            [
                'title' => 'First article',
                'body' => 'Text of the first article.',
                'published' => true,
                'created' => '2026-03-01 10:00:00',
                'modified' => '2026-03-01 10:00:00',
            ],
            [
                'title' => 'Second article',
                'body' => 'Text of the second article.',
                'published' => false,
                'created' => '2026-03-02 12:30:00',
                'modified' => '2026-03-02 12:30:00',
            ],
        ];
 
        $this->table('articles')->insert($data)->save();
    }
}

Each nested array is one table row and the keys are column names. The created and modified columns are filled by hand here: a seed writes to the database directly, bypassing table classes. In recent plugin versions the parent class is called BaseSeed.

Running

bin/cake migrations seed --seed ArticlesSeed

Two records appear in the articles table. Without the --seed option the command runs all seeds in the folder.

Many records

Data can be created in a loop:

public function run(): void
{
    $data = [];
 
    for ($i = 1; $i <= 20; $i++) {
        $data[] = [
            'title' => "Article #$i",
            'body' => 'Article text.',
            'published' => $i % 3 !== 0,
            'created' => date('Y-m-d H:i:s'),
            'modified' => date('Y-m-d H:i:s'),
        ];
    }
 
    $this->table('articles')->insert($data)->save();
}

The result is twenty articles, every third one unpublished. Such a set is enough to try pagination.

Migration or seed

What is neededWhat to use
Create a table, add a columnA migration
Fill a table with samples for developmentA seed
Add a reference list the site cannot work withoutA seed run during installation

Common mistake

Unlike migrations, seeds do not remember that they have already run. A second run adds the same records again and the table ends up with duplicates. Clear the table before running again, for example with the first line of the run() method: $this->table('articles')->truncate();.

Thanks for reading!

Donate to the site — we work hard for you.