Joren Van Hocht
Joren Van Hocht

Reputation: 865

Laravel Auth::user() relationships

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('[email protected]')->first()->role->name

What am I missing?

Upvotes: 3

Views: 9693

Answers (2)

Joren Van Hocht
Joren Van Hocht

Reputation: 865

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.

Upvotes: -1

Jeff Lambert
Jeff Lambert

Reputation: 24661

Auth::user can return a non-object when no user is logged in. You can use Auth::check() to guard against this, or even Auth::user itself:

if(!($user = Auth::user())) {
    // No user logged in
} else {
    $role = $user->role;
}

Alternatively:

if(Auth::check()) {
    $role = Auth::user()->role;
}

Upvotes: 4

Related Questions