ajimoti/roles-and-permissions

在您的Laravel应用程序中实现角色和权限,支持多对多关系(枢纽表)。

1.1.2 2022-01-24 12:20 UTC

README

Banner

简介

此包允许您将角色和权限分配给任何Laravel模型,或在枢纽表(多对多关系)上。

Ajimoti Ibukun构建和编写

文档

您可以在以下位置阅读官方文档

快速示例

在模型上

以下示例解释了如何在安装后使用此包在模型上。

use App\Enums\Role;
use App\Enums\Permission;

// Assign a 'Super Admin' role to this user
$user->assign(Role::SuperAdmin);

// Check if the user has the role
$user->hasRole(Role::SuperAdmin);
// Or 
$user->isSuperAdmin(); // returns true

// Check if the user can perform a operation
$user->can(Permission::DeleteTransactions); 
// Or 
$user->canDeleteTransactions(); 

// Check if the user has multiple permissions
$user->holds(Permission::DeleteTransactions, Permission::BlockUsers);

枢纽表(多对多关系)

这展示了如何在多对多关系上使用此包。在此示例中,我们假设在我们的User模型中有一个merchant关系。此关系返回Laravel的BelongsToMany类的实例。

导入App\Enums\RoleApp\Enums\Permission类。

use App\Enums\Role;
use App\Enums\Permission;

// Sample merchant
$merchant = Merchant::where('name', 'wallmart')->first();

// Assign a 'Super Admin' role to this user on the selected merchant (wallmart)
$user->of($merchant)->assign(Role::SuperAdmin);

// Check if the user has a super admin role on the selected merchant (wallmart)
$user->of($merchant)->hasRole(Role::SuperAdmin);

// Check if the user can 'delete transactions' on the selected merchant (wallmart)
$user->of($merchant)->can(Permission::DeleteTransactions);

// Check if the user has multiple permissions on the selected merchant (wallmart)
$user->of($merchant)->holds(Permission::DeleteTransactions, Permission::BlockUsers);

我们使用user模型来制作示例,与包上面的示例类似,此包将在任何模型类上工作。

要求

  • PHP 8.0或更高版本
  • Laravel 8.0或更高版本
  • 安装后,该包发布了一个config/roles-and-permissions.php文件,请确保您的配置目录中没有同名文件。

优点

  • 此包可用于任何模型,即任何模型都可以分配角色和权限。
  • 角色可以赋予多个权限。
  • 模型通过角色拥有权限。
  • 模型可以分配多个角色。
  • 可以分配角色给多对多关系。(即该包可用于枢纽表)。
  • 支持角色层次结构。(较高层级的角色可以配置为具有较低级别角色的权限)。

定时任务

  • 不能直接在多对多关系上分配权限。

安装

您可以通过composer安装此包

composer require ajimoti/roles-and-permissions

如果您想在现有的枢纽表上应用此包,可以将表名添加到config/roles-and-permissions.php配置文件中的pivot.tables数组中。以下命令将向数组中提供的每个枢纽表添加一个role列。

运行以下命令后,您就可以使用此包了。

php artisan roles:install

文档

访问https://roles.ajimoti.com/docs/intro以更好地了解如何使用此包。

测试

composer test

变更日志

请参阅CHANGELOG以了解最近有哪些更改。

贡献

请参阅CONTRIBUTING以获取详细信息。

安全漏洞

请参阅我们如何报告安全漏洞的安全策略

鸣谢

许可协议

MIT 许可证。请参阅许可文件获取更多信息。