How get the current user in model

Hi, I’m new using adonis and i really liked, but the documentation is poor. I hope in the future improve. :slight_smile:

well, I want know, is possible get the user (auth) in the model?

Hi @cognitus

you can use getUser() (Returns the logged in user instance)

const user = await auth.getUser()

@CrBast
get auth only is possible from view or controller, if it’s invoked from model, return unexpected token, cause auth is not defined :frowning:

Sorry, misread the question.
What exactly do you want to do with auth object in the model?

@CrBast
I usually program the logic in model, i could move to controller, but it is not the idea.
other case, create menus and submenus depending (relationship) of current user. So at least, I need the id of current user.

You can add auth as function parameter in your model and then get User instance

@CrBast

can you give me an example?

Hi @cognitus.

You could try make like this:

Controller:

async checkRelationship ({ auth }) {
    const menus = await Menu.checkUser(auth.getUser());

    return menus
}

Model:

checkUser (auth) {
   if (auth.id === 1)  {
      //have permission
   } else {
      //doesn't have permission
   }
}
2 Likes

@guiRibas

ok, but is possible “inject” the auth in model? via service provider or hook for example.

1 Like

Hello @cognitus. I don’t know if is possible do it :pensive: