Home > PHP Framework > Laravel > Let's talk about the permission management expansion package in Laravel

Let's talk about the permission management expansion package in Laravel

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2022-06-06 19:42:39
forward
4027 people have browsed it

This article brings you relevant knowledge about laravel, which mainly introduces the issues related to the expansion package of permission permission management. Let’s take a look at it together. I hope it will be helpful to everyone.

Let's talk about the permission management expansion package in Laravel

[Related recommendations: laravel video tutorial]

What is a multi-user role

For example, For example, the forum we usually use

Webmaster------has the highest authority, and the most important thing is the authority to manage users

Administrator-----For some The management of articles will not have a major impact on the website

vip ----- Have download permission for some resources

Ordinary users ---- can only make simple edits Additions, deletions, modifications, comments, etc. of your own articles

Visitors ---- can only perform basic browsing

Create tables


  • roles ------- Role information: Webmaster, etc.
  • permissions ------- Permission information: Management content, etc.
  • model_has_roles ------- Role corresponding to the model = Role corresponding to the user
  • role_has_permissions ------- Permission corresponding to the role = What permissions does the role have
  • model_has_permissions ----- -- Model corresponding permissions = Users have permissions

Let’s sort out the relationships

##Permissions (permissions) and Role (roles), one permission may be owned by multiple roles, and one role may have multiple permissions. Association relationship: many-to-many (role_has_permissions)

User and Permissions One-to-many (model_has_permissions)

User and Role One-to-many (model_has_roles)

By times Said, the relationship is clear, when the user has what role or what permissions, the corresponding operation is performed

1. Install the extension package

composer require "spatie/laravel-permission:~2.7"
Copy after login
Generate database migration file:

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"

You can see related table information in the migration directory and perform database migration

php artisan migrate
Copy after login
Generate configuration information:

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config"
Copy after login
Load under the User model

.....
use Spatie\Permission\Traits\HasRoles;  // use

class User extends Authenticatable
{

    use HasRoles;  // 加载角色相关信息
    .....
Copy after login
Create roles and users

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

.....
$role = Role::create(['name' => 'writer']);  // 创建角色
$permission = Permission::create(['name' => 'edit articles']);// 创建权限
Copy after login

Use


Add permissions for users

$user->givePermissionTo('edit articles');
Copy after login
Add roles for users

$user->assignRole('writer');

$user->assignRole(['writer', 'admin']);
Copy after login
Delete permissions for users

$user->revokePermissionTo('edit articles');
Copy after login
Add permissions for roles

$role->givePermissionTo('edit articles');
Copy after login
Copy after login
Add permissions for roles Permissions

$role->givePermissionTo('edit articles');
Copy after login
Copy after login
Revoke a permission and add a new one

$user->syncPermissions(['edit articles', 'delete articles']);
Copy after login
Get the current user's role collection

$user->getRoleNames();
Copy after login
Synchronize multiple roles to permissions

$role->syncPermissions($permissions); //  @param array $permissions

$permission->syncRoles($roles);
Copy after login
Remove permissions from a role

$role->revokePermissionTo($permission);
$permission->removeRole($role);
Copy after login
Get the current user's permission list

$permissions = $user->permissions;
Copy after login
Get all the user's permissions, or direct permissions (odel_has_permissions), or get it from the role, or get it from both

$permissions = $user->getDirectPermissions();
$permissions = $user->getPermissionsViaRoles();
$permissions = $user->getAllPermissions();
Copy after login
Get the user's role collection collection

$roles = $user->getRoleNames(); // Returns a collection
Copy after login
Returns users with the specified role | Returns only users with the role 'writer'

$users = User::role('writer')->get(); //
Copy after login
Returns users with the specified permissions

$users = User::permission('edit articles')->get();
Copy after login
What roles does the user have

$user->hasRole('writer');
Copy after login

Verification class


Check whether there is a certain permission

$user->hasPermissionTo('edit articles');

$user->can('edit articles');
Copy after login
Check whether there is a certain role | Or column

$user->hasRole('writer');

$user->hasAnyRole(Role::all());

$user->hasAllRoles(Role::all());
Copy after login
pass the id value to determine whether there is a certain permission

$user->hasPermissionTo('1');
$user->hasPermissionTo(Permission::find(1)->id);
$user->hasPermissionTo($somePermission->id);
Copy after login
Whether it has a set of permissions

$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);
Copy after login
Check whether a role has certain permissions | Delete a certain These permissions

$role->hasPermissionTo('edit articles'); 

$role->revokePermissionTo('edit articles'); // 删除
Copy after login

template uses

@role('writer')
    I am a writer!
@else
    I am not a writer...
@endrole

------------------------

@hasrole('writer')
    I am a writer!
@else
    I am not a writer...
@endhasrole

------------------------

@can('edit articles') // 拥有某个权限 可执行操作
//
@endcan
Copy after login

data to fill
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // Reset cached roles and permissions
        app()['cache']->forget('spatie.permission.cache');

        // create permissions
        Permission::create(['name' => 'edit articles']);
        Permission::create(['name' => 'delete articles']);
        Permission::create(['name' => 'publish articles']);
        Permission::create(['name' => 'unpublish articles']);

        // create roles and assign created permissions

        $role = Role::create(['name' => 'writer']);
        $role->givePermissionTo('edit articles');

        $role = Role::create(['name' => 'moderator']);
        $role->givePermissionTo(['publish articles', 'unpublish articles']);

        $role = Role::create(['name' => 'super-admin']);
        $role->givePermissionTo(Permission::all());
    }
}
Copy after login

Tip: If in the database To modify the permission-related information table, you must use the method of clearing the cache
// 命令删除
php artisan cache:forget spatie.permission.cache  

app()['cache']->forget('spatie.permission.cache');
Copy after login

[Related recommendations:

laravel video tutorial]

The above is the detailed content of Let's talk about the permission management expansion package in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Composer cannot install laravel
From 1970-01-01 08:00:00
0
0
0
Laravel Space/laravel-backup cannot be installed
From 1970-01-01 08:00:00
0
0
0
Laravel 5.1 Login laravel comes with it No more
From 1970-01-01 08:00:00
0
0
0
Why thinkphp has better performance than laravel?
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template