PHPackages                             shiwuhao/laravel-rbac - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. shiwuhao/laravel-rbac

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

shiwuhao/laravel-rbac
=====================

A modern Laravel 12+ RBAC package with data permissions and auto-sync features.

v1.4.1(2y ago)11.9kMITPHP

Since Jan 7Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/shiwuhao/laravel-rbac)[ Packagist](https://packagist.org/packages/shiwuhao/laravel-rbac)[ RSS](/packages/shiwuhao-laravel-rbac/feed)WikiDiscussions master Synced yesterday

READMEChangelog (7)Dependencies (2)Versions (10)Used By (0)

Laravel RBAC
============

[](#laravel-rbac)

 [ ![Latest Stable Version](https://camo.githubusercontent.com/ffbaab744afc65c64fde554136fe3833a6d5fd75b0f19f5ecceedd073c3e35e6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736869777568616f2f6c61726176656c2d726261632e7376673f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/shiwuhao/laravel-rbac) [ ![PHP Version](https://camo.githubusercontent.com/b2e5e1304ab4683de68f57e13ba1beb9eea928bf021ac1f4a6ec2a6f59d5b279/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f736869777568616f2f6c61726176656c2d726261632e7376673f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/shiwuhao/laravel-rbac) [ ![License](https://camo.githubusercontent.com/20ebce3574b1821064c724b0a8047b112fb650b131cc33ca82eb4676f3ebb345/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f736869777568616f2f6c61726176656c2d726261632e7376673f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/shiwuhao/laravel-rbac)

> 现代化的 Laravel 12+ RBAC 扩展包，采用 Action 模式架构，提供完整的基于角色的访问控制（RBAC）和数据权限管理功能。

---

📖 文档导航
------

[](#-文档导航)

文档说明**[完整使用指南](docs/USAGE.md)**详细的 API 使用、路由配置、权限管理等**[命令行工具](docs/COMMANDS.md)**Artisan 命令详解和使用示例**[快速开始](#-%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B)**安装配置和基本用法**[更新日志](CHANGELOG.md)**版本变更记录✨ 特性
----

[](#-特性)

- 🎯 **Action 模式架构** - 路由直接绑定 Action，无需控制器中间层
- 🔐 **完整的 RBAC 实现** - 角色、权限、数据范围管理
- 🚀 **开箱即用** - 内置完整的 CRUD Actions 和 RESTful API 路由
- 📦 **高度解耦** - 通过配置支持自定义用户模型
- 🎨 **优雅的 API** - 统一的上下文访问和响应处理
- 📝 **完善的注解** - 权限注解和 PHPDoc 注释
- 🔧 **灵活扩展** - 可发布 Actions 到项目中自定义

📋 版本要求
------

[](#-版本要求)

PackageLaravelPHP2.0.x12.x&gt;= 8.2📦 安装
----

[](#-安装)

```
composer require shiwuhao/laravel-rbac
```

### 发布配置和迁移文件

[](#发布配置和迁移文件)

```
# 发布所有文件
php artisan vendor:publish --provider="Rbac\RbacServiceProvider"

# 或者分别发布
php artisan vendor:publish --tag=rbac-config
php artisan vendor:publish --tag=rbac-migrations
php artisan vendor:publish --tag=rbac-routes
```

### 运行迁移

[](#运行迁移)

```
php artisan migrate
```

🎯 核心架构 - Action 模式
------------------

[](#-核心架构---action-模式)

### 什么是 Action 模式？

[](#什么是-action-模式)

Action 是一个独立的业务逻辑单元，每个 Action 负责一个具体的业务操作。

```
// 路由直接绑定 Action
Route::post('/roles', CreateRole::class);
Route::put('/roles/{id}', UpdateRole::class);
```

### Action 的优势

[](#action-的优势)

- ✅ **单一职责** - 每个 Action 只做一件事
- ✅ **可测试性强** - 独立的类，易于单元测试
- ✅ **可复用** - 可在控制器、命令、队列中调用
- ✅ **类型安全** - 完整的类型提示和返回值定义

🚀 快速开始
------

[](#-快速开始)

### 1. 安装依赖

[](#1-安装依赖)

```
composer require shiwuhao/laravel-rbac
```

### 2. 发布配置和迁移

[](#2-发布配置和迁移)

```
php artisan vendor:publish --provider="Rbac\RbacServiceProvider"
php artisan migrate
```

### 3. 配置用户模型

[](#3-配置用户模型)

在 `.env` 中配置：

```
RBAC_USER_MODEL=App\Models\User
```

或在 `config/rbac.php` 中配置：

```
'models' => [
    'user' => \App\Models\User::class,
],
```

### 4. 在用户模型中使用 Trait

[](#4-在用户模型中使用-trait)

```
use Rbac\Traits\HasRolesAndPermissions;

class User extends Authenticatable
{
    use HasRolesAndPermissions;
}
```

### 5. 开始使用

[](#5-开始使用)

```
use Rbac\Actions\Role\CreateRole;

// 创建角色
$role = CreateRole::handle([
    'name' => '管理员',
    'slug' => 'admin',
]);
```

> 💡 **更多详细用法请查看** → [完整使用指南](docs/USAGE.md)

📚 核心功能
------

[](#-核心功能)

### 角色管理

[](#角色管理)

```
use Rbac\Actions\Role\CreateRole;

$role = CreateRole::handle([
    'name' => '管理员',
    'slug' => 'admin',
]);
```

### 权限管理

[](#权限管理)

```
use Rbac\Actions\Permission\CreatePermission;

$permission = CreatePermission::handle([
    'name' => '创建用户',
    'slug' => 'user:create',
]);
```

### 权限检查

[](#权限检查)

```
// 代码中
if (auth()->user()->hasPermission('user:create')) {
    // 有权限
}

// Blade 模板中
@permission('user:create')
    创建用户
@endpermission

// 路由中间件
Route::get('/users', [UserController::class, 'index'])
    ->middleware('permission:user:view');
```

> 📖 **详细 API 文档** → [完整使用指南](docs/USAGE.md)
> 🔧 **命令行工具** → [Artisan 命令](docs/COMMANDS.md)

🎨 高级功能
------

[](#-高级功能)

### 数据范围权限

[](#数据范围权限)

```
use Rbac\Actions\DataScope\CreateDataScope;

// 创建简单数据范围
$scope = CreateDataScope::handle([
    'name' => '部门数据',
    'type' => 'department',
]);

// 创建带动态表达式的自定义数据范围
$scope = CreateDataScope::handle([
    'name' => '最近30天数据',
    'slug' => 'recent-30-days',
    'type' => 'custom',
    'config' => [
        'rules' => [
            ['field' => 'created_at', 'operator' => '>=', 'value' => '@now-30d:date'],
            ['field' => 'status', 'operator' => 'IN', 'value' => ['active', 'pending']],
        ],
        'logic' => 'AND',
    ],
    'description' => '只能访问最近30天的活跃数据（运行时动态计算）',
]);
```

#### 动态表达式支持

[](#动态表达式支持)

自定义数据范围支持在 `config` 中使用动态表达式，运行时自动解析：

**时间表达式：**

```
'@now'              // 当前时间
'@now-30d'          // 30天前
'@now-3M'           // 3个月前
'@now-1y'           // 1年前
'@now+7d'           // 7天后
'@now-30d:date'     // 30天前（仅日期）
'@now-30d:timestamp' // 30天前（时间戳）
```

**用户属性表达式：**

```
'@user.id'              // 当前用户ID
'@user.department_id'   // 用户部门ID
'@user.organization_id' // 用户组织ID
```

**使用示例：**

```
// 限制只能访问自己部门最近一周的数据
CreateDataScope::handle([
    'name' => '本部门本周数据',
    'type' => 'custom',
    'config' => [
        'rules' => [
            ['field' => 'department_id', 'operator' => '=', 'value' => '@user.department_id'],
            ['field' => 'created_at', 'operator' => '>=', 'value' => '@now-7d:datetime'],
        ],
        'logic' => 'AND',
    ],
]);
```

### 实例权限

[](#实例权限)

```
use Rbac\Actions\Permission\CreateInstancePermission;

// 为特定文章创建权限
$permission = CreateInstancePermission::handle([
    'resource' => 'article',
    'resource_id' => 123,
    'action' => 'update',
]);
```

### 自定义 Action

[](#自定义-action)

```
use Rbac\Actions\BaseAction;

class CustomAction extends BaseAction
{
    protected function rules(): array
    {
        return ['name' => 'required|string'];
    }

    protected function execute(): mixed
    {
        return $this->context->data('name');
    }
}
```

> 📖 **更多高级用法** → [完整使用指南](docs/USAGE.md)

🔧 Artisan 命令
------------

[](#-artisan-命令)

```
# 扫描并生成权限节点
php artisan rbac:scan-permissions

# 清除权限缓存
php artisan rbac:clear-cache

# 查看权限统计
php artisan rbac:permission-stats
```

> 🔧 **完整命令列表** → [命令行工具文档](docs/COMMANDS.md)

⚙️ 配置选项
-------

[](#️-配置选项)

主要配置项：

```
return [
    // 自定义用户模型
    'models' => [
        'user' => \App\Models\User::class,
    ],

    // API 路由配置
    'api' => [
        'enabled' => true,
        'prefix' => 'api/rbac',
        'middleware' => ['api', 'auth:sanctum'],
    ],
];
```

> 📖 **完整配置说明** → [完整使用指南](docs/USAGE.md#%E9%85%8D%E7%BD%AE)

📝 License
---------

[](#-license)

MIT License. 详见 [LICENSE](LICENSE) 文件。

🤝 贡献
----

[](#-贡献)

欢迎提交 Issue 和 Pull Request！

👤 作者
----

[](#-作者)

- **shiwuhao** -

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance50

Moderate activity, may be stable

Popularity17

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~82 days

Recently: every ~52 days

Total

8

Last Release

1007d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/95b8b040655d3dea1d87d8422d9f105756c4433c174d6874f1e44bff12fdf21f?d=identicon)[shiwuhao](/maintainers/shiwuhao)

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/shiwuhao-laravel-rbac/health.svg)

```
[![Health](https://phpackages.com/badges/shiwuhao-laravel-rbac/health.svg)](https://phpackages.com/packages/shiwuhao-laravel-rbac)
```

###  Alternatives

[namshi/jose

JSON Object Signing and Encryption library for PHP.

1.8k99.6M101](/packages/namshi-jose)[league/oauth1-client

OAuth 1.0 Client Library

99698.8M106](/packages/league-oauth1-client)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[gesdinet/jwt-refresh-token-bundle

Implements a refresh token system over Json Web Tokens in Symfony

70516.4M35](/packages/gesdinet-jwt-refresh-token-bundle)[league/oauth2-google

Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client

41721.2M118](/packages/league-oauth2-google)[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
