thiagoprz/simple-role

Laravel 包,用于将基于角色的认证系统添加到任何项目中

0.0.11 2022-04-08 16:57 UTC

This package is auto-updated.

Last update: 2024-09-08 22:12:17 UTC


README

向任何 Laravel 项目添加基于角色的认证系统的包。

安装和使用

composer require thiagoprz/simple-role

运行迁移,将角色列添加到您的用户表中,例如:php artisan migrate

使用可枚举特性添加角色

... 
use Thiagoprz\SimpleRole\Enrollable;
...
class User ...
{
    Use Enrollable;
    ...    
}

此特性将为 User 模型添加 setRole($role) 方法,您可以使用它来更新用户角色

$user->setRole('admin')

使用 Laravel 标准属性添加角色

如果您不想使用可枚举特性,可以将 'role' 列添加到 User 模型的 fillable 属性中

class User
{
    ...
    protected $fillable = [
        'name', 'email', 'password', ... , 'role',
    ];
    ...    
}

定义您将工作的不同类型的角色,并使用中间件来处理上面的路由

web.php

// Route enrolment will be only acessible to "employee" users
Route::get('enrolment', 'EnrolmentController@index')->middleware('role:employee');

// Routes inside Admin namespace will be only acessible to users with the role "admin"
Route::namespace('Admin')->middleware(['auth', 'role:admin'])->group(function() {
...
});

// Routes inside Customer namespace will be only acessible to users with the role "customer"
Route::namespace('Customer')->middleware(['auth', 'role:customer'])->group(function() {
...
});

一个路由可以要求多个角色,为此只需添加以逗号分隔的角色。

// Route enrolment will be only acessible to "employee" users
Route::get('product', 'ProductController')->middleware('role:admin,manager,employee');

我了解到其他包可以以更强大的方式完成相同的功能,允许多个角色和其他功能,但这个包提供了最简单的方法来实现这一点,并允许小型项目以较小的占用运行简单的基于角色的系统。