调用 Laravel 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

}

这是第二种方法


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()调用数据库吗!!!?


千巷猫影
浏览 79回答 2
2回答

慕斯709654

auth()->user()当您使用或关系(已加载/设置)时,它不会进行多次调用。您可以安装发条并检查它。不过,我不会在 User 类之外进行这些比较。将这些方法添加到您的用户模型中。public function isAdmin(){    return $this->role === 'admin';}public function isSupervised(){    return $this->role === 'supervised';}并像这样使用它们;auth()->user()->isAdmin()

月关宝盒

我会使用第一种方法,而不是创建不必要的变量。它不会多次调用数据库。查看user()中的方法SessionGaurd.php// 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;}
打开App,查看更多内容
随时随地看视频慕课网APP