@stouder-io/adonis-translatable
v1.1.0
Published
Translatable fields for AdonisJS models.
Downloads
21
Maintainers
Readme
Installation
This package is available in the npm registry.
pnpm i @stouder-io/adonis-translatable
Usage
After installing the package, you can now decorate your translatable fields with the @translation
decorator.
class Post extends BaseModel {
@column()
declare id: number
@translation()
declare title: Translation
@translation()
declare body: Translation
}
In your migrations, the translatable fields must be of type json
.
export default class extends BaseSchema {
protected tableName = 'posts'
async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments('id')
table.json('title')
table.json('body')
})
}
async down() {
this.schema.dropTable(this.tableName)
}
}
When using your model, you can now access the translated fields.
const post = await Post.find(1)
post.title.get('fr')
You can access it and throw if it doesn't exist.
const post = await Post.find(1)
post.title.getOrFail('fr')
You can also set the translated fields.
const post = await Post.find(1)
post.title.set('fr', 'Mon titre')
Or fully replace the translations.
const post = await Post.find(1)
post.title = Translation.from({
fr: 'Mon titre',
en: 'My title',
})