auth.user in Lucid Hooks
I would like to have a hook that before create and update to store the logged in user information
const auth = use('Auth')
class User extends Model {
static boot () {
super.boot()
this.addHook('beforeCreate', async (userInstance) => {
userInstance.created_by = auth.user.id
})
this.addHook('beforeUpdate', async (userInstance) => {
userInstance.created_by = auth.user.id
})
}
}
How can I implement like this?
The auth instance is not a global variable and neither can be saved globally. You can pass it manually from your controller.
In short, hook is not the right place to do it, you must do it inside controller or create a re-usable function on model, which takes the user id and performs the save for you
OKOK.
Then I may pass the auth from the controller of every create or update action
Yes
Is this still the case?
Surely we should have access to the Users Id in either a Trait or a Hook?
I've registered a trait to override the CREATED_AT and UPDATED_AT columns to be CREATED_DATE and UPDATED_DATE to match our schema. In turn i'd also like to be able to populate CREATED_BY and UPDATED_BY columns using hooks.
const Model = use('Model')
class Contact extends Model {
static boot() {
super.boot()
this.addTrait('CreatedUpdated')
}
...
}
'use strict'
const Db = use('Database')
class CreatedUpdated {
// The purpose of this trait is to ensure that
// created_at, updated_at, created_by and updated_by columns are matched correctly
// and are also hidden from the frontend
register(Model, options) {
Object.defineProperties(Model, {
createdAtColumn: {
get: () => 'CREATED_DATE',
},
updatedAtColumn: {
get: () => 'UPDATED_DATE',
},
createdByColumn: {
get: () => 'CREATED_USER',
},
updatedByColumn: {
get: () => 'UPDATED_USER',
},
hidden: {
get: () => ['CREATED_DATE', 'UPDATED_DATE', 'CREATED_USER', 'UPDATED_USER', 'PASSWORD', 'SALT']
}
})
Model.addHook('beforeCreate', async (thisInstance) => {
const createdDate = Db.fn.now()
thisInstance.CREATED_DATE = createdDate
thisInstance.UPDATED_DATE = createdDate
// I want to pass the Auth.getUser().id into these rather than 999
thisInstance.CREATED_BY = 999
thisInstance.UPDATED_BY = 999
})
Model.addHook('beforeUpdate', async (thisInstance) => {
const updatedDate = Db.fn.now()
thisInstance.UPDATED_DATE = updatedDate
// I want to pass the Auth.getUser().id into this rather than 999
thisInstance.UPDATED_BY = 999
})
}
}
module.exports = CreatedUpdated
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.