> adonis make:trait Slugify
You are viewing the legacy version of AdonisJS. Visit https://adonisjs.com for newer docs. This version will receive security patches until the end of 2021.
Traits make it possible to add functionality to models from the outside in.
Using model traits, you can:
Add new methods to your model class.
Listen for model hooks.
Add methods to the Query Builder instance for a given model.
Traits are stored in the app/Models/Traits
directory.
Use the make:trait
command to generate a trait file:
> adonis make:trait Slugify
✔ create app/Models/Traits/Slugify.js
Traits require a register
method receiving the Model
class and an customOptions
object as its parameters:
'use strict'
class Slugify {
register (Model, customOptions = {}) {
const defaultOptions = {}
const options = Object.assign(defaultOptions, customOptions)
}
}
module.exports = Slugify
Add a trait to a Lucid model like so:
const Model = use('Model')
class User extends Model {
static boot () {
super.boot()
this.addTrait('Slugify')
}
}
If required, you can pass initialization options when adding a trait:
const Model = use('Model')
class User extends Model {
static boot () {
super.boot()
this.addTrait('Slugify', {useCamelCase: true})
}
}
The options you pass will be forwarded to the trait’s register()
method.
When passing options, it’s recommended you define default trait options like so:
const _ = require('lodash')
class Slugify {
register (Model, customOptions) {
const defaultOptions = {useCamelCase: false}
const options = _.extend({}, defaultOptions, customOptions)
}
}
module.exports = Slugify
Use traits to add static and instance model methods:
class Slugify {
register (Model, options) {
// Add a static method
Model.newAdminUser = function () {
let m = new Model()
m.isAdmin = true
return m
}
// Add an instance method
Model.prototype.printUsername = function () {
console.log(this.username)
}
}
}
module.exports = Slugify
Use traits to hook into database lifecycle events:
class Slugify {
register (Model, options) {
Model.addHook('beforeCreate', function (modelInstance) {
// create slug
})
}
}
module.exports = Slugify
Use traits to add macros to a model’s Query Builder:
class Slugify {
register (Model, options) {
Model.queryMacro('whereSlug', function (value) {
this.where('slug', value)
return this
})
}
}
module.exports = Slugify
await User.query().whereSlug('some value')