为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
千巷猫影 2023-07-01 17:23:51
我有一个简单的用户表-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()调用数据库吗!!!?
查看完整描述

2 回答

?
慕斯709654

TA贡献1840条经验 获得超5个赞

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


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


public function isAdmin()

{

    return $this->role === 'admin';

}


public function isSupervised()

{

    return $this->role === 'supervised';

}

并像这样使用它们;


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


查看完整回答
反对 回复 2023-07-01
?
月关宝盒

TA贡献1772条经验 获得超5个赞

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

}


查看完整回答
反对 回复 2023-07-01
  • 2 回答
  • 0 关注
  • 75 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信