gpt4 book ai didi

php - 调用 Laravel Auth 辅助方法的最佳方式

转载 作者:行者123 更新时间:2023-12-02 19:24:05 25 4
gpt4 key购买 nike

我有一个简单的用户表

-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() 每次我调用它时都会调用数据库吗!!!?

最佳答案

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

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

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

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

并像这样使用它们;

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

关于php - 调用 Laravel Auth 辅助方法的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62623873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com