Laravel Auth::user() relationships

2019-03-31 20:56发布

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?

2条回答
混吃等死
2楼-- · 2019-03-31 21:22

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;
}
查看更多
三岁会撩人
3楼-- · 2019-03-31 21:33

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.

查看更多
登录 后发表回答