Php 调用Laravel Auth helper方法的最佳方法

Php 调用Laravel Auth helper方法的最佳方法,php,laravel,authentication,Php,Laravel,Authentication,我有一个简单的用户表 -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 } $auth = auth()

我有一个简单的用户表

-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
}
$auth = auth()->user();
if($user->role == 'admin')
{
   // do something
}
else if ($user->role == 'supervised')
{
  // do something
}
else{
  //this is a simple user
}
这是第二种方法

2.

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

这个方法每次调用数据库时都调用它吗

我将使用第一个方法,而不是创建一个不必要的变量。它不会多次调用数据库。查看
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;
}

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

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

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

public function isSupervised()
{
    return $this->role === 'supervised';
}
像这样使用它们

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

@拉娜·侯赛因先生,为什么?@MRanaHossain你能告诉我为什么第二个更好吗?谢谢你的回答。您是否尝试在auth()中更新当前用户?例如,如果在重新加载页面后更新名称,您将发现该用户是自动从database@KokoMonsef更新之后,它没有发出新请求(可能在类中设置值并从中返回)。但是如果您
auth()->user()->refresh()
这样做,那么它将向数据库发出新的请求。