I am trying to get my users role relation through the Auth::user() function. I have done this before but for some reason it is not working.
Auth::user()->role
This returns the error trying to get property from non-object.
In my user model I have this:
public function role()
{
return $this->belongsTo('vendor\package\Models\Role');
}
In my role model I have:
public function user()
{
return $this->hasMany('vendor\package\Models\User');
}
When I do this it returns the name of my role, so my relations are correct I think:
User::whereEmail('test@test.be')->first()->role->name
What am I missing?
Auth::user
can return a non-object when no user is logged in. You can useAuth::check()
to guard against this, or evenAuth::user
itself:Alternatively:
Ok I found out why it wasn't working for me. The thing is that my User model where I was talking about was a part of my package, and because Laravel has it's own User model in the default Laravel installation it was not working.
Your package model does not override an already existing model. I solved my problem by making a Trait instead of a model for my package.