Skip to main content

Database: Seeding

See how to create and run database seeders.

Introduction

Athenna includes the ability to seed your database with data using seed classes. All seed classes are stored in the Path.seeders() directory.

Writing seeders

To generate a seeder, execute the make:seeder Artisan command. All seeders generated by the framework will be placed in the Path.seeders() directory:

node artisan make:seeder UserSeeder

A seeder class only contains one method by default: run(). This method is called when the db:seed Artisan command is executed. Within the run() method, you may insert data into your database however you wish. You may use the query builder to manually insert data, or you may use the model factories:

import { User } from '#app/models/user'
import { BaseSeeder, type DatabaseImpl } from '@athenna/database'

export class UserSeeder extends BaseSeeder {
public async run(db: DatabaseImpl) {
await db.table('users').createMany([/*.....*/])

await User.factory().count(20).create()
}
}

Running seeders

You may execute the db:seed Artisan command to seed your database. By default, the db:seed command will run all the seeders inside the Path.seeders() folder, but you can run only one seeder using the --classes argument:

node artisan db:seed

node artisan db:seed --classes=UserSeeder

Setting the seeder connection

If your seeder will be interacting with a database connection other than your application's default database connection, you should set the static method connection() in your seeder:

import { BaseSeeder, type DatabaseImpl } from '@athenna/database'

export class UserSeeder extends BaseSeeder {
public static connection() {
return 'postgres'
}

public async run(db: DatabaseImpl) {
await Database.table('users').createMany([/*.....*/])

await User.factory().count(20).create()
}
}