【问题标题】:best way to call Laravel Auth helper method调用 Laravel Auth 辅助方法的最佳方法
【发布时间】:2020-06-28 14:27:38
【问题描述】:

我有一个简单的用户表

-id
-name
-email
-role

我应该使用第一种还是第二种方法?!

第一种方法

1.

if(auth()->user()->role == 'admin')
{
   // do something
}
else if (auth()->user()->role == 'supervised')
{
  // do something
}
else{
  //this is a simple user
}

这是第二种方法

2.

$auth = auth()->user();
if($user->role == 'admin')
{
   // do something
}
else if ($user->role == 'supervised')
{
  // do something
}
else{
  //this is a simple user
}

这个方法auth()->user()每次我调用它时都会调用数据库吗!!!?

【问题讨论】:

  • @M Rana Hossain,为什么?
  • @MRanaHossain 你能告诉我为什么第二个更好吗?

标签: php laravel authentication


【解决方案1】:

当您使用auth()->user() 或关系(已加载/设置)时,它不会进行多次调用。您可以安装clockwork 并检查它。

不过,我不会在 User 类之外进行这些比较。将这些方法添加到您的用户模型中。

public function isAdmin()
{
    return $this->role === 'admin';
}

public function isSupervised()
{
    return $this->role === 'supervised';
}

并像使用它们;

auth()->user()->isAdmin()

【讨论】:

  • 感谢您的回答。您是否尝试在 auth() 中更新当前用户,例如,如果您在页面重新加载后更新名称,您会发现该用户是自动从数据库中选择的
  • @KokoMonsef 更新后它没有发出新请求(可能在类中设置值并从它返回)。但是如果你auth()->user()->refresh() 这样做,那么它将向数据库发出新请求。
【解决方案2】:

我会使用第一种方法而不是创建不必要的变量。它不会多次调用数据库。查看SessionGaurd.php中的user()方法

// If we've already retrieved the user for the current request we can just
// return it back immediately. We do not want to fetch the user data on
// every call to this method because that would be tremendously slow.
if (! is_null($this->user)) {
    return $this->user;
}

【讨论】:

    猜你喜欢
    • 2016-06-22
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2011-03-27
    • 2015-07-28
    相关资源
    最近更新 更多