当前使用的版本是laravel 5.2 在使用和Zizaco/entrust 5.2这个包的时候,怎么获得当前登录用户的角色?
namespace App\Services;
use App\User;
use Zizaco\Entrust\EntrustRole;
use Illuminate\Support\Facades\Cache;
class NameAndRole
{
public $username;
public $role;
public function __construct() {
$user = \Auth::user();
$this->username = $user->name;
$role = ; //怎么获得当前登录用户的角色?
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在你的users模型以及roles模型里,应该有像下边这样的方法:
模型里边有了以上方法,获取角色就像下边这样(访问动态属性):
使用entrust不用在模型中重新方法定义,entrust已经封装过了。在vendor/zizacao/entrust/scr/Entrust/Traits/EntrustUserTrait.php 中的roles方法已经定义了。
获取用户所属角色使用:$user->roles->display_name