Auth.user. (other fields)


#1

Hi,

I have two tables:

  • users (id, username, email, password)
  • profiles (id, user_id, name, surname)

Models/user.js :

user() {
	return this.belongsTo('App/Models/User', 'id' , 'user_id')
}

Models/profile.js :

profile() {
    return this.hasOne('App/Models/Profile', 'id', 'user_id')
}

How can I recover other fields from my table profiles with:

auth.user.surname
or
auth.user.name

Is there a way to set the object so that it retrieves fields from related tables?

Thanks


#2

The way you defined the relationships between the models is wrong. They should be like this (and please switch the models, unless if you did a typo):
Models/Profile.js :

user() {
  return this.belongsTo('App/Models/User')
}

Models/User.js :

profile() {
  return this.hasOne('App/Models/Profile')
}

Also, you do not need to define the relationships in both directions.


#3

I made the modifications
I still can not recover the value of:
auth.user.surname


#4

I am not sure what you are trying to do, but that is not how you can access user information. Maybe something like this:

// Attempt to log in the user
if (await auth.attempt(email, password)) { 
  // See if a user exists based on the email and password he typed
  let user = await User.findBy('email', email)
  // Generate an access token for him
  let accessToken = await auth.generate(user)

Put all the above code in a try block, so that if user did not exist, you do not generate the JWT token


#5

UserController.js :

	async index({view, auth}){
		const user = await auth.getUser()
		const profile = await user.profile().fetch()
		return view.render('home.index',{profile})
	}

home/index.edge :

{{ auth.user.surname}} // undefined
{{ profile.surname}} // true

#6

As far as I know you are looking for something which is in profile table…
So that accessing profile.surname from authenticated user will give you the answer… That’s how you set the relationship


#7

So we can not modify the Auth object so that it retrieves info from the profiles table in this way “auth.user.surname”?


#8

Hey everyone! :wave:

I believe that the answer I gave in the following thread fixes this issue.