Track Created By / Modified By for Records in AdonisJS

AdonisJS provided a quick way to track created and updated times, but does not provide shortcuts to track the user who created or last updated the record. Doing so is quite easy.

Modify the migration script to include created_by_id and updated_by_id.

// todoschema.js
class TodoSchema extends Schema {
  up() {
    this.create("todos", table => {
      table.increments(); // id
      table.timestamps(); // created_at and updated_at columns
      table
        .integer("created_by_id")
        .unsigned()
        .references("id")
        .inTable("users");
      table
        .integer("updated_by_id")
        .unsigned()
        .references("id")
        .inTable("users");
    });
  }

  down() {
    this.drop("todos");
  }
}

module.exports = TodoSchema;

Both the user id columns are references to the users table, which is included out of the box in Adonis.

You can now update these values for your create or update operations. You can do this in more than one way - a simple approach using controllers is shown below.

Introduce code in create and update methods in your controller.

// TodoController.js
const user = await auth.getUser();
todo["created_by_id"] = user.id; // only in create
todo["updated_by_id"] = user.id; // in create and update methods
comments powered by Disqus