简体   繁体   English

Laravel Auth :: user()关系

[英]Laravel Auth::user() relationships

I am trying to get my users role relation through the Auth::user() function. 我试图通过Auth :: user()函数获取我的用户角色关系。 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 use Auth::check() to guard against this, or even Auth::user itself: 当没有用户登录时, Auth::user可以返回非对象。您可以使用Auth::check()来防止这种情况,甚至可以使用Auth::user本身:

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

Alternatively: 或者:

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

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. 问题是我所说的用户模型是我的软件包的一部分,并且因为Laravel在默认的Laravel安装中拥有自己的用户模型,所以它无法正常工作。

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. 我通过制作Trait而不是我的包的模型解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM