laravel-permission
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLaravel Permission (Spatie)
Laravel Permission (Spatie)
Agent Workflow (MANDATORY)
Agent工作流(必填)
Before ANY implementation, use to spawn 3 agents:
TeamCreate- fuse-ai-pilot:explore-codebase - Check existing auth patterns
- fuse-ai-pilot:research-expert - Verify Spatie Permission docs via Context7
- mcp__context7__query-docs - Check Laravel authorization patterns
After implementation, run fuse-ai-pilot:sniper for validation.
在进行任何实现之前,使用生成3个Agent:
TeamCreate- fuse-ai-pilot:explore-codebase - 检查现有身份验证模式
- fuse-ai-pilot:research-expert - 通过Context7验证Spatie Permission文档
- mcp__context7__query-docs - 检查Laravel授权模式
实现完成后,运行fuse-ai-pilot:sniper进行验证。
Overview
概述
Spatie Laravel Permission provides complete role-based access control (RBAC) for Laravel applications.
| Component | Purpose |
|---|---|
| Role | Group of permissions (admin, writer) |
| Permission | Single ability (edit articles) |
| Middleware | Route protection |
| Blade Directives | UI authorization |
| Teams | Multi-tenant scoping |
| Wildcards | Hierarchical permissions |
| Super Admin | Bypass all checks |
| Events | Audit logging (v6.15.0+) |
| Query Scopes | Filter users by role/permission |
| API Support | Sanctum/Passport integration |
| Policies | Resource-based authorization |
Spatie Laravel Permission为Laravel应用提供完整的基于角色的访问控制(RBAC)能力。
| 组件 | 用途 |
|---|---|
| Role | 权限集合(管理员、内容创作者) |
| Permission | 单个操作权限(编辑文章) |
| Middleware | 路由保护 |
| Blade Directives | UI层授权判断 |
| Teams | 多租户权限隔离 |
| Wildcards | 层级化权限管理 |
| Super Admin | 绕过所有权限校验 |
| Events | 审计日志(v6.15.0+支持) |
| Query Scopes | 按角色/权限筛选用户 |
| API Support | 集成Sanctum/Passport |
| Policies | 基于资源的授权 |
Critical Rules
关键规则
- Seed roles/permissions in
DatabaseSeeder - Cache reset after changes:
php artisan permission:cache-reset - Use kebab-case for naming:
edit-articles - Never hardcode role checks in controllers - use middleware
- Set team context early in request for multi-tenant apps
- Specify guard for API -
permission:edit,api - Clear cache in tests - Reset in setUp()/beforeEach()
- 在中预填充角色/权限
DatabaseSeeder - 权限修改后重置缓存:
php artisan permission:cache-reset - 权限命名使用kebab-case格式:例如
edit-articles - 禁止在控制器中硬编码角色校验 - 请使用中间件实现
- 多租户应用需在请求生命周期早期设置团队上下文
- API场景需指定看守器:
permission:edit,api - 测试中需清空权限缓存 - 在setUp()/beforeEach()中执行重置
Reference Guide
参考指南
Core Concepts
核心概念
| Topic | Reference | When to consult |
|---|---|---|
| Setup | spatie-permission.md | Installation, model setup, core methods |
| Middleware | middleware.md | Route protection patterns |
| Blade | blade-directives.md | UI authorization directives |
| Direct vs Role | direct-permissions.md | Permission inheritance |
| 主题 | 参考文档 | 适用场景 |
|---|---|---|
| 基础配置 | spatie-permission.md | 安装、模型配置、核心方法使用 |
| 中间件 | middleware.md | 路由保护实现方案 |
| Blade指令 | blade-directives.md | UI层授权指令使用 |
| 直接权限vs角色权限 | direct-permissions.md | 权限继承逻辑说明 |
Advanced Features
高级功能
| Topic | Reference | When to consult |
|---|---|---|
| Teams | teams.md | Multi-tenant permissions |
| Wildcards | wildcard-permissions.md | Hierarchical patterns |
| Super Admin | super-admin.md | Bypass all permissions |
| Custom Models | custom-models.md | UUID, extending models |
| 主题 | 参考文档 | 适用场景 |
|---|---|---|
| 团队权限 | teams.md | 多租户权限管理 |
| 通配符权限 | wildcard-permissions.md | 层级化权限配置 |
| 超级管理员 | super-admin.md | 全局权限绕过配置 |
| 自定义模型 | custom-models.md | UUID支持、模型扩展 |
Integration
集成方案
| Topic | Reference | When to consult |
|---|---|---|
| API Usage | api-usage.md | Sanctum, guards, JSON responses |
| Policies | policies.md | Laravel Policy integration |
| Query Scopes | query-scopes.md | |
| Events | events.md | Audit logging, notifications |
| 主题 | 参考文档 | 适用场景 |
|---|---|---|
| API使用 | api-usage.md | Sanctum集成、看守器配置、JSON响应处理 |
| 策略集成 | policies.md | Laravel Policy集成 |
| 查询作用域 | query-scopes.md | |
| 事件 | events.md | 审计日志、通知触发 |
Operations & Quality
运维与质量
| Topic | Reference | When to consult |
|---|---|---|
| Cache | cache.md | Performance, debugging |
| CLI | artisan-commands.md | Artisan commands |
| Testing | testing.md | Tests, factories, setup |
| Performance | performance.md | Optimization, N+1, caching |
| 主题 | 参考文档 | 适用场景 |
|---|---|---|
| 缓存管理 | cache.md | 性能优化、问题排查 |
| CLI命令 | artisan-commands.md | Artisan命令使用 |
| 测试 | testing.md | 测试用例编写、工厂配置、环境初始化 |
| 性能优化 | performance.md | 优化方案、N+1问题解决、缓存配置 |
Templates (Code Examples)
模板(代码示例)
Setup & Seeding
配置与数据填充
| Template | Purpose |
|---|---|
| UserModel.php.md | User model with HasRoles trait |
| RoleSeeder.php.md | Basic role seeding |
| PermissionSeeder.php.md | Permission creation seeder |
| WildcardSeeder.php.md | Hierarchical permissions |
| 模板 | 用途 |
|---|---|
| UserModel.php.md | 集成HasRoles trait的用户模型 |
| RoleSeeder.php.md | 基础角色填充脚本 |
| PermissionSeeder.php.md | 权限创建填充脚本 |
| WildcardSeeder.php.md | 层级化权限配置脚本 |
Routes & Middleware
路由与中间件
| Template | Purpose |
|---|---|
| routes-example.md | Protected routes examples |
| ControllerMiddleware.php.md | Middleware in controllers |
| BladeExamples.blade.md | Blade directive examples |
| 模板 | 用途 |
|---|---|
| routes-example.md | 受保护路由示例 |
| ControllerMiddleware.php.md | 控制器中使用中间件示例 |
| BladeExamples.blade.md | Blade指令使用示例 |
Teams & Multi-Tenant
团队与多租户
| Template | Purpose |
|---|---|
| TeamMiddleware.php.md | Multi-tenant middleware |
| TeamSeeder.php.md | Team-scoped roles seeder |
| TeamModel.php.md | Team model with boot |
| 模板 | 用途 |
|---|---|
| TeamMiddleware.php.md | 多租户中间件 |
| TeamSeeder.php.md | 团队维度角色填充脚本 |
| TeamModel.php.md | 带启动配置的团队模型 |
Super Admin & Cache
超级管理员与缓存
| Template | Purpose |
|---|---|
| SuperAdminSetup.php.md | Gate::before bypass |
| CacheConfig.php.md | Cache configuration |
| DeployScript.sh.md | CI/CD cache management |
| 模板 | 用途 |
|---|---|
| SuperAdminSetup.php.md | Gate::before权限绕过配置 |
| CacheConfig.php.md | 缓存配置 |
| DeployScript.sh.md | CI/CD流程中的缓存管理 |
API Integration
API集成
| Template | Purpose |
|---|---|
| ApiPermissionSetup.php.md | API guard + Sanctum |
| ApiExceptionHandler.php.md | JSON error responses |
| ApiUserResource.php.md | User resource with permissions |
| 模板 | 用途 |
|---|---|
| ApiPermissionSetup.php.md | API看守器+Sanctum配置 |
| ApiExceptionHandler.php.md | JSON错误响应处理 |
| ApiUserResource.php.md | 携带权限信息的用户资源类 |
Policies & Events
策略与事件
| Template | Purpose |
|---|---|
| PostPolicy.php.md | Policy with Spatie integration |
| PermissionEventListener.php.md | Audit event listeners |
| UserQueryExamples.php.md | Query scope examples |
| PermissionAudit.php.md | Audit service |
| 模板 | 用途 |
|---|---|
| PostPolicy.php.md | 集成Spatie的Policy示例 |
| PermissionEventListener.php.md | 审计事件监听器 |
| UserQueryExamples.php.md | 查询作用域使用示例 |
| PermissionAudit.php.md | 审计服务实现 |
Testing
测试
| Template | Purpose |
|---|---|
| PermissionTest.php.md | Pest & PHPUnit tests |
| UserFactory.php.md | Factory with permission states |
| 模板 | 用途 |
|---|---|
| PermissionTest.php.md | Pest & PHPUnit测试用例 |
| UserFactory.php.md | 带权限状态的用户工厂 |
Custom Models
自定义模型
| Template | Purpose |
|---|---|
| CustomRole.php.md | Extended Role model |
| CustomPermission.php.md | Extended Permission model |
| UUIDMigration.php.md | UUID tables migration |
| SetupPermissions.php.md | Custom artisan command |
| 模板 | 用途 |
|---|---|
| CustomRole.php.md | 扩展后的Role模型 |
| CustomPermission.php.md | 扩展后的Permission模型 |
| UUIDMigration.php.md | UUID表迁移文件 |
| SetupPermissions.php.md | 自定义Artisan命令 |
Quick Reference
快速参考
Assign Role
分配角色
php
$user->assignRole('admin');php
$user->assignRole('admin');Check Permission
权限校验
php
$user->can('edit articles');php
$user->can('edit articles');Middleware (Web)
中间件(Web端)
php
Route::middleware(['role:admin'])->group(fn () => ...);php
Route::middleware(['role:admin'])->group(fn () => ...);Middleware (API)
中间件(API端)
php
Route::middleware(['auth:sanctum', 'permission:edit,api'])->group(fn () => ...);php
Route::middleware(['auth:sanctum', 'permission:edit,api'])->group(fn () => ...);Blade
Blade模板
blade
@role('admin') ... @endrole
@can('edit articles') ... @endcanblade
@role('admin') ... @endrole
@can('edit articles') ... @endcanQuery Scopes
查询作用域
php
User::role('admin')->get();
User::permission('edit articles')->get();php
User::role('admin')->get();
User::permission('edit articles')->get();Teams
团队权限
php
setPermissionsTeamId($team->id);php
setPermissionsTeamId($team->id);Wildcards
通配符权限
php
$role->givePermissionTo('articles.*');php
$role->givePermissionTo('articles.*');Super Admin
超级管理员
php
Gate::before(fn ($user, $ability) =>
$user->hasRole('Super-Admin') ? true : null
);php
Gate::before(fn ($user, $ability) =>
$user->hasRole('Super-Admin') ? true : null
);Testing
测试配置
php
beforeEach(fn () => app(PermissionRegistrar::class)->forgetCachedPermissions());php
beforeEach(fn () => app(PermissionRegistrar::class)->forgetCachedPermissions());Feature Matrix
功能矩阵
| Feature | Status | Reference |
|---|---|---|
| Basic RBAC | ✅ | spatie-permission.md |
| Middleware | ✅ | middleware.md |
| Blade Directives | ✅ | blade-directives.md |
| Multi-Guard (web/api) | ✅ | middleware.md, api-usage.md |
| Teams (Multi-Tenant) | ✅ | teams.md |
| Wildcard Permissions | ✅ | wildcard-permissions.md |
| Super Admin | ✅ | super-admin.md |
| Cache Management | ✅ | cache.md |
| Direct vs Role Perms | ✅ | direct-permissions.md |
| Artisan Commands | ✅ | artisan-commands.md |
| UUID Support | ✅ | custom-models.md |
| Custom Models | ✅ | custom-models.md |
| Events (v6.15.0+) | ✅ | events.md |
| Query Scopes | ✅ | query-scopes.md |
| Policy Integration | ✅ | policies.md |
| API / Sanctum | ✅ | api-usage.md |
| Testing | ✅ | testing.md |
| Performance | ✅ | performance.md |
| 功能 | 支持状态 | 参考文档 |
|---|---|---|
| 基础RBAC | ✅ | spatie-permission.md |
| 中间件 | ✅ | middleware.md |
| Blade指令 | ✅ | blade-directives.md |
| 多看守器(web/api) | ✅ | middleware.md, api-usage.md |
| 团队权限(多租户) | ✅ | teams.md |
| 通配符权限 | ✅ | wildcard-permissions.md |
| 超级管理员 | ✅ | super-admin.md |
| 缓存管理 | ✅ | cache.md |
| 直接权限/角色权限 | ✅ | direct-permissions.md |
| Artisan命令 | ✅ | artisan-commands.md |
| UUID支持 | ✅ | custom-models.md |
| 自定义模型 | ✅ | custom-models.md |
| 事件(v6.15.0+) | ✅ | events.md |
| 查询作用域 | ✅ | query-scopes.md |
| Policy集成 | ✅ | policies.md |
| API/Sanctum集成 | ✅ | api-usage.md |
| 测试支持 | ✅ | testing.md |
| 性能优化 | ✅ | performance.md |