Home  >  Article  >  PHP Framework  >  laravel-permission role permission control [detailed code explanation]

laravel-permission role permission control [detailed code explanation]

藏色散人
藏色散人forward
2020-06-20 13:33:178223browse

The following tutorial column of Laravel will introduce you to laravel-permission role permission control. I hope it will be helpful to friends in need!

laravel-permission role permission control [detailed code explanation]

First of all, post the GitHub address

https://github.com/spatie/laravel-permission

Then let’s talk about the usage experience

Let’s first talk about the table structure of the database. There are 6 tables in total. You can also add, modify and delete tables according to your preference. But let’s make the list first!

The first is the user table (users). Needless to say, it contains some basic information including name, email address and so on!

Permissions table (permissions) is a table that stores all permissions. Permissions can be controller access permissions, interface access permissions, and model access permissions. Here we only discuss interface access permissions!

Role table (roles) The role table stores all your characters, and the name of the character is the index!

Now that we have the basic tables, how are they related? please watch the following part!

The user has permissions table (model_has_permissions). This table records the many-to-many relationship table of user_id and permission_id. The user obtains permissions directly.

The user has roles table (model_has_roles). This table records the permissions that the user has. The table contains user_id and role_id. This is also a many-to-many relationship table that records users and roles. It can also be understood as an intermediate table!

The role has permissions table (role_has_permissions). This table records what permissions the role has. There are only two fields in the table: role_id, permission_id! It can also be expanded as needed!

The following is a picture to visually see each relationship:


Users have direct permissions , model_has_permissions, if the user has a role, then it is model_has_role and then go to the roles table role_has_permission

How to add a role (the dependency package provides a method)

$role = Role::Create(['name' => 'add_title']);

How many parameters does Create have? There is a name and guard_name in the original method, as shown in the following code

use Spatie\Permission\Models\Role;
public static function create(array $attributes = [])
{
    $attributes['guard_name'] = $attributes['guard_name'] ?? config('auth.defaults.guard');

    if (static::where('name', $attributes['name'])->where('guard_name', $attributes['guard_name'])->first()) {
        throw RoleAlreadyExists::create($attributes['name'], $attributes['guard_name']);
    }

    if (isNotLumen() && app()::VERSION < &#39;5.4&#39;) {
        return parent::create($attributes);
    }

    return static::query()->create($attributes);
}

We can also use this method instead of calling its original task. For example, the task

is called in the seeder that comes with project initialization.
namespace App\Containers\Authorization\Data\Seeders;
Apiato::call(&#39;Authorization@CreateRoleTask&#39;, [&#39;admin&#39;, &#39;Administrator&#39;, &#39;Administrator Role&#39;, 999,&#39;admin&#39;]);

You can find the seeder by following the namespace address. This task is also in the Task under Authorization. You can modify the Task to meet your own needs!

How to add permissions (dependency packages also provide methods)

$ permission  =  Permission :: create([ ' name '  =>  ' edit articles ' ]);

Like role, you can also find a written Task and its create method! Not much to say here!

How to directly add permissions to users, delete permissions, and determine whether they have permissions

//可以授予任何用户权限:
$ user - > givePermissionTo(' edit articles ');

//你也可以一次给多个权限
$ user - > givePermissionTo( ' edit articles ', ' delete articles ');

//你也可以传递数组
$ user - > givePermissionTo([ ' edit articles ', ' delete articles ' ]);
//权限可以从用户撤销:
$ user - > revokePermissionTo(' edit articles ');
//或者一次性撤消并添加新的权限:
$ user - > syncPermissions([ ' edit articles ',' delete articles ' ]);
//您可以测试用户是否有权限:
$ user - > hasPermissionTo(' edit articles ');
//测试用户有多个权限:
$ user - > hasAnyPermission([ ' edit articles ',' publish articles ',' unpublish articles ' ]);
//您可以使用Laravel的默认can功能测试用户是否具有权限:
$ user - > can(' edit articles ');

How to use permissions through roles

//角色可以分配给任何用户:
$ user - > assignRole(' writer ');

//你也可以一次赋值多个角色
$ user - > assignRole( ' writer ', ' admin ');
//或者作为一个数组
$ user - > assignRole([ ' writer ', ' admin ' ]);
//角色可以从用户中删除:
$ user - > removeRole(' writer ');
//角色也可以同步:
//所有当前角色将被从用户中删除,而由传入的数组取代
$ user - > syncRoles([ ' writer ', ' admin ' ]);
//您可以确定用户是否具有某个角色:
$ user - > hasRole(' writer ');
//您还可以确定用户是否有任何给定的角色列表:
$ user - > hasAnyRole(Role :: all());
//您还可以确定用户是否具有所有给定的角色列表:
$ user - > hasAllRoles(Role :: all());
//assignRole,hasRole,hasAnyRole,hasAllRoles 和removeRole函数可以接受一个字符串,
//一个\Spatie\Permission\Models\Role对象或一个\Illuminate\Support\Collection对象。

//可以给角色一个许可:
$ role - > givePermissionTo(' edit articles ');
//您可以确定角色是否具有某种权限:
$ role - > hasPermissionTo(' edit articles ');
//权限可以从角色中被撤销:
$ role - > revokePermissionTo(' edit articles ');
//该givePermissionTo和revokePermissionTo函数可以接受字符串或Spatie\Permission\Models\Permission对象。
//权限是从角色自动继承的。另外,个人权限也可以分配给用户。例如:
$ role  =  Role :: findByName(' writer '); 
$ role - > givePermissionTo(' edit articles ');
$ user - > assignRole(' writer ');
$ user - > givePermissionTo(' delete articles ');
//在上面的例子中,角色被授予编辑文章的权限,并且该角色被分配给用户。现在,用户可以编辑文章并删除文章。
//“删除文章”的权限是直接分配给用户的直接权限。
//当我们调用$user->hasDirectPermission('delete articles')它返回true,
//但false对$user->hasDirectPermission('edit articles')。
//如果为应用程序中的角色和用户设置权限并希望限制或更改用户角色的继承权限(即,仅允许更改用户的直接权限),则此方法非常有用。
//您可以列出所有这些权限:
//直接权限
$ user - > getDirectPermissions() //或$ user-> permissions;

//从用户角色继承的权限
$ user - > getPermissionsViaRoles();

//所有适用于用户的权限(继承和直接)
$ user - > getAllPermissions();
//所有这些响应都是Spatie\Permission\Models\Permission对象的集合。
//如果我们按照前面的例子,第一个响应将是一个具有delete article权限的集合,

Where to make restrictions and where to use

First of all, you can check whether the user has this permission in the action!

You can also use it in request. When the user requests an interface, the system will determine whether the user has the permissions and roles to pass this interface!

Of course this request must be injected when the interface calls the method!

The location is given below

//第二个响应将是一个具有权限的集合,edit article第三个将包含这两个集合。

Summary:

laravel has several role permission controls, but I choose this one, laravel-permission is easy to search, It’s not because who is better or who is worse! In general, role permissions consist of role tables and permission tables, and then there is the relationship maintenance between users, roles, and permissions! In fact, you don’t have to use his own methods!

The relationship between the basic tables is many-to-many. You can use attach, detch, and sync to maintain the relationship between them!

If you are familiar enough with the game, you don’t need his relationship table. You can write it yourself to realize this 10% relationship!

The above is the detailed content of laravel-permission role permission control [detailed code explanation]. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete