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

Traits make it possible to add functionality to models from the outside in.

Using model traits, you can:

  1. Add new methods to your model class.

  2. Listen for model hooks.

  3. Add methods to the Query Builder instance for a given model.

Creating a Trait

Traits are stored in the app/Models/Traits directory.

Use the make:trait command to generate a trait file:

> adonis make:trait Slugify
Output
✔ create  app/Models/Traits/Slugify.js

Traits require a register method receiving the Model class and an customOptions object as its parameters:

app/Models/Traits/Slugify.js
'use strict'

class Slugify {
  register (Model, customOptions = {}) {
    const defaultOptions = {}
    const options = Object.assign(defaultOptions, customOptions)
  }
}

module.exports = Slugify

Registering a Trait

Add a trait to a Lucid model like so:

const Model = use('Model')

class User extends Model {
  static boot () {
    super.boot()
    this.addTrait('Slugify')
  }
}

Registering a Trait with Options

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:

app/Models/Traits/Slugify.js
const _ = require('lodash')

class Slugify {

  register (Model, customOptions) {
    const defaultOptions = {useCamelCase: false}
    const options = _.extend({}, defaultOptions, customOptions)
  }
}

module.exports = Slugify

Extending Model Methods

Use traits to add static and instance model methods:

app/Models/Traits/Slugify.js
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

Adding Model Hooks

Use traits to hook into database lifecycle events:

class Slugify {

  register (Model, options) {
    Model.addHook('beforeCreate', function (modelInstance) {
      // create slug
    })
  }
}

module.exports = Slugify

Extending Query Builder

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
Usage
await User.query().whereSlug('some value')