I've used Eloquent hasOne to create a relationship between the user and the users_permissions table when the user register's to the website and group the user according to the input they put on the form and it worked fine, but the same method I think it does not recognize when the same user is signed in the website.
我已经使用Eloquent hasOne在用户注册到网站时创建用户和users_permissions表之间的关系,并根据他们在表单上输入的内容对用户进行分组,并且工作正常,但我认为它的方法相同无法识别同一用户何时在网站上签名。
The below code work's when the user sign-up to the website
当用户注册网站时,以下代码工作
$user->permissions()->create(UserPermission::user_group($nature_of_entity));
But when I want to use the below method it, I get an error Trying to get property of non-object.
但是当我想使用下面的方法时,我得到一个错误试图获取非对象的属性。
public function hasPermission($permission) {
return (bool) $this->permissions->$permission;
}
public function permissions() {
return $this->hasOne('App\User\UserPermission', 'user_id');
}
In the user database a table named users_permissions that has (id, user_id, is_group_one, is_group_two, is_group_three)
在用户数据库中,名为users_permissions的表具有(id,user_id,is_group_one,is_group_two,is_group_three)
I'm trying to see it the user is in which group, like:
我试图看到用户在哪个组中,例如:
if($app->user->hasPermission('is_group_one')){
echo 'Group One';
}
But I get an error Trying to get property of non-object. I'd really appreciate it if any can help and if they are ways I could do this and use Laravel Eloquent Relationships methods. I hope you can understand what I mean.
但我得到一个错误试图获得非对象的属性。我真的很感激,如果有任何可以帮助,如果他们是我可以做到这一点,并使用Laravel Eloquent Relationships方法。我希望你能明白我的意思。
1 个解决方案
#1
1
Create a scope that queries through the permissions relationship and checks if the column (i.e. $permission) is TRUE. Axe the (bool)
bit...
创建一个通过权限关系查询的范围,并检查列(即$ permission)是否为TRUE。 Ax(bool)位......
public function scopeHasPermission($query, $permission)
{
return $query->permissions->where($permission, true);
}
Then in your controller, keep this the same as you had it:
然后在你的控制器中,保持它与你一样:
if($app->user->hasPermission('is_group_one')) {
...
}
#1
1
Create a scope that queries through the permissions relationship and checks if the column (i.e. $permission) is TRUE. Axe the (bool)
bit...
创建一个通过权限关系查询的范围,并检查列(即$ permission)是否为TRUE。 Ax(bool)位......
public function scopeHasPermission($query, $permission)
{
return $query->permissions->where($permission, true);
}
Then in your controller, keep this the same as you had it:
然后在你的控制器中,保持它与你一样:
if($app->user->hasPermission('is_group_one')) {
...
}