Laravel Auth::user() 关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28990995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:07:31  来源:igfitidea点击:

Laravel Auth::user() relationships

phpauthenticationlaraveleloquent

提问by Joren Van Hocht

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() 函数获取我的用户角色关系。我以前这样做过,但由于某种原因它不起作用。

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?

我错过了什么?

采纳答案by Joren Van Hocht

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.

好的,我发现了为什么它对我不起作用。问题是我所说的 User 模型是我包的一部分,因为 Laravel 在默认的 Laravel 安装中有它自己的 User 模型,所以它不起作用。

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 而不是一个模型来解决我的问题。

回答by Jeff Lambert

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

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;
}