Before we implement the logic of adding new posts, we need some dummy posts. You can create new posts by running SQL queries inside your database interface, but that will defeat the whole purpose of rapid development and re-usability.
There are plenty of use cases for Database Factories and Seeds, but for now, we will use them to create some dummy blog posts.
database/factory.js
'use strict'
const Factory = use('Factory')
Factory.blueprint('App/Model/Post', (fake) => {
return {
title: fake.sentence(),
content: fake.paragraph()
}
})
Factories let you define blueprints for your models. Each blueprint takes the model name as the first parameter and a callback as the second parameter. Callback get’s access to the chancejs instance, which is used to generate random data.
Next, we need to make use of the defined blueprint inside the database/seeds/Database.js
file.
database/seeds/Database.js
'use strict'
const Factory = use('Factory')
class DatabaseSeeder {
* run () {
yield Factory.model('App/Model/Post').create(5) (1)
}
}
module.exports = DatabaseSeeder
1 |
Here we make use of the blueprint and create five posts using the create method. |
Finally, we need to seed this file by running an ace command.
Output
✔ seeded database successfully