>我有一个简单的用户表
-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
}
每次调用数据库时,此方法是否auth()->user()
调用!!?
当您使用auth()->user()
或关系(它是加载/设置的(时,它不会进行多次调用。您可以安装发条并检查它。
不过,我不会在 User 类之外进行这些比较。 将这些方法添加到用户模型中。
public function isAdmin()
{
return $this->role === 'admin';
}
public function isSupervised()
{
return $this->role === 'supervised';
}
并像使用它们一样使用它们;
auth()->user()->isAdmin()
我会使用第一种方法而不是创建一个不必要的变量。它不会对数据库进行多次调用。查看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;
}