有谁能帮我解决问题吗?
我正在 Laravel 中创建一个区域,用户可以在其中根据自己的角色登录。
使用 artisan 命令创建身份验证,到目前为止非常简单。
然后,我开始更改数据库中表“users”的表名和主键。 完成此操作后,需要更新用户模型(由 artisan 命令自动生成)并让模型知道表“users”的确切位置以及哪个是该表的主键。
protected $table = 'users';
protected $primaryKey = 'userID';
在此之后,一旦我转到浏览器并进行正常登录,它就不允许我访问管理仪表板,并且我收到提示试图获取非-对象。
这是因为一旦表和主键像我之前所做的那样被更改,'$this' 就不再在对象上下文中了。
我怎样才能让它发挥作用?
用户.php:
class User extends Authenticatable
{
(...) public function isAdmin(){
if($this->roles->Role_Type == "Admin" && $this->is_active == 1){ //this one is the line 83 where the error is
return true;
}
return false;
}
(...)
}
最佳答案
这段代码有错误
$this->roles->Role_Type
"$this->roles"返回与该用户对应的角色,然后您使用字段“Role_Type”。
在您的场景中,该用户没有附加任何角色。
所以这个“$this->roles”返回空值。
所以你不能取值“Role_Type”。这会导致错误。
您必须执行以下操作
if($this->roles != null && $this->roles->Role_Type && $this->is_active == 1) {
return true;
} else {
return false;
}
注意:您的代码将与 has one 关系一起工作。
Class User extends Model
{
public function roles()
{
return $this->hasOne('App\Role');
}
}
如果你想以高效的方式使用角色和权限,试试这个包https://github.com/romanbican/roles
关于php - 拉维尔 5.3 : Can not access anymore the admin dashboard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40152302/