search
HomePHP FrameworkLaravellaravel-permission role permission control [detailed code explanation]

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. If there is any infringement, please contact admin@php.cn delete
Laravel framework skills sharingLaravel framework skills sharingApr 18, 2025 pm 01:12 PM

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

The difference between laravel and thinkphpThe difference between laravel and thinkphpApr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Laravel user login function listLaravel user login function listApr 18, 2025 pm 01:06 PM

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.

What versions of laravel are there? How to choose the version of laravel for beginnersWhat versions of laravel are there? How to choose the version of laravel for beginnersApr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

How to view the version number of laravel? How to view the version number of laravelHow to view the version number of laravel? How to view the version number of laravelApr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

The latest method of using php framework laravelThe latest method of using php framework laravelApr 18, 2025 pm 12:57 PM

Laravel is a popular PHP-based web application framework that is popular among developers for its elegant syntax and powerful features. Its latest version introduces many improvements and new features designed to improve the development experience and application performance. This article will dive into Laravel's latest approach, focusing on how to leverage these updates to build more powerful and efficient web applications.

Laravel framework installation methodLaravel framework installation methodApr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

How to learn Laravel How to learn Laravel for freeHow to learn Laravel How to learn Laravel for freeApr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor