简体   繁体   English

Laravel 权限表 pivot 表

[英]Laravel permissions pivot table

I am making custom permissions ,我正在制作自定义权限

I would like them to be divided into sections eg orders, customers etc. and each section would have some permission eg edit, delete, add.我希望将它们分成多个部分,例如订单、客户等,每个部分都有一些权限,例如编辑、删除、添加。 Just to check if a particular user has access I would have to start with the Section model?只是为了检查特定用户是否有权访问,我必须从 model 部分开始?

Because I can't do something like Auth::user()->permissions()->with('sections')->contains('name','display')->contains('sections','order')因为我不能做类似Auth::user()->permissions()->with('sections')->contains('name','display')->contains('sections','order')

I would like to simply check if the user has access to, for example, order.display .我想简单地检查用户是否有权访问,例如order.display I have a feeling that this section does not make sense here.我有一种感觉,这部分在这里没有意义。

How to do it?怎么做? I know there is a spatie(laravel-permission), but there is a role division there.我知道有一个 spatie(laravel-permission),但是那里有一个角色划分。

Example schema of the database (user_permission is a pivot):数据库的示例模式(user_permission 是一个枢轴): 在此处输入图像描述

My advice is if you're looking for something simple, drop the sections table and just have all permissions in the permissions table.我的建议是,如果您正在寻找简单的东西,请删除 section 表并在permissions表中拥有所有权限。 Say you had a section called dashboard in permissions you could have view_dashboard edit_dashboard etc. Then to check the user is authorised, implement the hasManyThrough logic below Official documentation假设您在权限中有一个名为dashboard的部分,您可以拥有view_dashboard edit_dashboard等。然后要检查用户是否已授权,请在官方文档下方实现hasManyThrough逻辑

(untested) (未经测试)

public function permissions()
{
    return $this->hasManyThrough(Permissions::class, UserPermissions::class);
}

public function permission_check($permission_to_check)
{
    return $this->permissions->contains($permission_to_check);
}

You could then eager load permissions() on the user model to reduce DB queries if you are checking permission in many places.然后,如果您在许多地方检查权限,您可以急切地在用户 model 上加载permissions()以减少数据库查询。

Hope this helps, let me know if I can assist further:)希望这会有所帮助,如果我能提供进一步的帮助,请告诉我:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM