在 Laravel 4 中返回当前用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18559736/
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 08:22:08  来源:igfitidea点击:

Return current User in Laravel 4

phplaravellaravel-4

提问by JasonDavis

Using PHP and Laravel 4 I have a method in my User model like this below to check for Admin user...

使用 PHP 和 Laravel 4 我在我的用户模型中有一个像下面这样的方法来检查管理员用户......

public function isAdmin()
{
    if(isset($this->user_role)  && $this->user_role === 'admin'){
        return true;
    }else{
        return false;
    }
}

This doesn't work when I call this function in other classes or models though.

但是,当我在其他类或模型中调用此函数时,这不起作用。

To get the desired result I had to do it like this instead...

为了得到想要的结果,我不得不这样做......

public function isAdmin()
{
    if(isset(Auth::user()->user_role)  && Auth::user()->user_role === 'admin'){
        return true;
    }else{
        return false;
    }
}

I am trying to access this inside my Admin Controller like this below but it returns an empty User object instead of current logged in user Object...

我试图像下面这样在我的管理控制器中访问它,但它返回一个空的用户对象而不是当前登录的用户对象......

public function __construct(User $user)
{
    $this->user = $user;
}

So my question is how can I get the first version to work? When I instantiate a User object in another class, I need to somehow make sure it has the data for the current logged in user but I am not sure the best way to do that...I know this is basic I am just a little rusty right now could use the help, thanks

所以我的问题是如何让第一个版本工作?当我在另一个类中实例化一个 User 对象时,我需要以某种方式确保它具有当前登录用户的数据,但我不确定最好的方法......我知道这是基本的我只是一点点rusty 现在可以使用帮助,谢谢

回答by Laurence

This returns the user repository - not the current logged in user

这将返回用户存储库 - 而不是当前登录的用户

public function __construct(User $user)

To access the current logged in user ANYWHERE in your application - just do

要在您的应用程序中的任何地方访问当前登录的用户 - 只需执行

Auth::user()

(like your middle example)

(就像你的中间例子)

So therefore - to check if a user is an admin user ANYWHERE in your application - just do

因此 - 要检查用户是否是您应用程序中任何地方的管理员用户 - 只需执行

if (Auth::user()->isAdmin())
{
     // yes
}
else
{
     // no
}