iamgerwin/nova-spatie-role-permission
Composer 安装命令:
composer require iamgerwin/nova-spatie-role-permission
包简介
A Laravel Nova tool for managing roles and permissions via Spatie Laravel Permission
README 文档
README
A comprehensive Laravel Nova tool for managing roles and permissions with Spatie's Laravel Permission package. Built for Laravel 11-12, Nova 5, and PHP 8.3+.
Features
- 🔐 Complete Role & Permission Management - Full CRUD operations for roles and permissions
- 🎨 Nova 5 Compatibility - Built specifically for the latest Laravel Nova
- 🚀 Laravel 12 Ready - Supports both Laravel 11 and 12
- 🔧 Flexible Configuration - Customize resources, policies, and guards
- 🌍 Multi-language Support - Ready for internationalization
- ⚡ Performance Optimized - Automatic cache management for permissions
- ✅ Fully Tested - Comprehensive test coverage with Pest
- 📱 User-friendly Interface - Intuitive boolean groups and select fields
Requirements
- PHP 8.3 or higher
- Laravel 11.0 or 12.0
- Laravel Nova 5.0 (required at runtime, not during installation)
- Spatie Laravel Permission 6.0
Installation
Step 1: Install the package
Install the package via composer:
composer require iamgerwin/nova-spatie-role-permission
Step 2: Publish Configuration (Optional but Recommended)
The package includes default configuration, but you can publish it for customization:
php artisan vendor:publish --provider="Iamgerwin\NovaSpatieRolePermission\ToolServiceProvider"
Step 3: Clear Caches
After installation, clear all caches to ensure proper loading:
php artisan config:clear php artisan cache:clear
Step 4: Set up Spatie Permissions
Publish and run the migrations from Spatie Laravel Permission if you haven't already:
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate
Step 5: Register the Tool
Register the tool in your NovaServiceProvider:
// app/Providers/NovaServiceProvider.php use Iamgerwin\NovaSpatieRolePermission\NovaSpatieRolePermissionTool; public function tools() { return [ new NovaSpatieRolePermissionTool(), ]; }
Note: Laravel Nova must be installed and configured in your application before using this package's features.
Quick Setup (Alternative)
For a faster setup, use the installation command which handles most of the above steps:
php artisan nova-permission:install
This command will:
- Publish the configuration file
- Clear permission cache
- Seed default permissions (optional)
- Create super-admin role with all permissions (optional)
- Assign super-admin role to a user (optional)
You can also use command options for non-interactive installation:
# Install with default permissions and super-admin role php artisan nova-permission:install --seed # Install and assign super-admin to a specific user php artisan nova-permission:install --seed --super-admin=admin@example.com
Configuration
Publish the configuration file to customize the package:
php artisan vendor:publish --tag=nova-permission-config
This will create config/nova-permission.php where you can customize:
- Default guard for roles and permissions
- Super admin role name
- Enable/disable permission checking
- Cache settings
- Default permissions for seeding
- Custom models, resources, and policies
Usage
Verify Installation
After installation, verify everything is properly configured:
php artisan nova-permission:verify
This command will check:
- Configuration file status
- Nova and Spatie Permission installation
- Database migrations
- Model configurations
- Nova resource registrations
Adding Roles and Permissions to User Resource
You can add role and permission fields to your User Nova resource in multiple ways:
Using MorphToMany Field (Recommended)
// app/Nova/User.php use Laravel\Nova\Fields\MorphToMany; use Iamgerwin\NovaSpatieRolePermission\Nova\Role; use Iamgerwin\NovaSpatieRolePermission\Nova\Permission; public function fields(NovaRequest $request) { return [ // ... other fields MorphToMany::make('Roles', 'roles', Role::class), MorphToMany::make('Permissions', 'permissions', Permission::class), ]; }
Using Boolean Group Fields
For a checkbox-style interface:
use Iamgerwin\NovaSpatieRolePermission\Fields\RoleBooleanGroup; use Iamgerwin\NovaSpatieRolePermission\Fields\PermissionBooleanGroup; public function fields(NovaRequest $request) { return [ // ... other fields RoleBooleanGroup::make('Roles', 'roles') ->options(app(config('permission.models.role'))->pluck('name', 'id')->toArray()), PermissionBooleanGroup::make('Permissions', 'permissions') ->options(app(config('permission.models.permission'))->pluck('name', 'id')->toArray()), ]; }
Using Select Field for Single Role
use Iamgerwin\NovaSpatieRolePermission\Fields\RoleSelect; public function fields(NovaRequest $request) { return [ // ... other fields RoleSelect::make('Role', 'role') ->options(app(config('permission.models.role'))->pluck('name', 'id')->toArray()) ->displayUsingLabels(), ]; }
Advanced Configuration
Custom Resources
You can use your own Nova resources:
use App\Nova\CustomRole; use App\Nova\CustomPermission; public function tools() { return [ (new NovaSpatieRolePermissionTool()) ->roleResource(CustomRole::class) ->permissionResource(CustomPermission::class), ]; }
Custom Policies
Define your own authorization policies:
use App\Policies\CustomRolePolicy; use App\Policies\CustomPermissionPolicy; public function tools() { return [ (new NovaSpatieRolePermissionTool()) ->rolePolicy(CustomRolePolicy::class) ->permissionPolicy(CustomPermissionPolicy::class), ]; }
Guard Configuration
Specify custom guards for roles and permissions:
public function tools() { return [ (new NovaSpatieRolePermissionTool()) ->roleGuard('admin') ->permissionGuard('api'), ]; }
Middleware
The package includes automatic permission cache clearing. To enable it, add the middleware to your Nova middleware group:
// app/Http/Kernel.php protected $middlewareGroups = [ 'nova' => [ // ... other middleware \Iamgerwin\NovaSpatieRolePermission\Http\Middleware\ForgetCachedPermissions::class, ], ];
Bulk Actions
The package includes a bulk action to attach permissions to roles:
use Iamgerwin\NovaSpatieRolePermission\Actions\AttachToRole; public function actions(NovaRequest $request) { return [ new AttachToRole, ]; }
Localization
The package supports internationalization. Publish the language files:
php artisan vendor:publish --tag="nova-spatie-role-permission-translations"
Available languages:
- English (en)
You can add your own translations in the resources/lang/vendor/nova-spatie-role-permission directory.
Authorization
As of version 1.1.0, the package includes secure default policies that check for actual permissions. The policies support granular permissions and a super admin role that bypasses all checks.
Default Permission Structure
The package's policies check for these permissions:
Role Management Permissions
view-roles- View role listings and detailscreate-roles- Create new rolesedit-roles- Update existing rolesdelete-roles- Delete rolesrestore-roles- Restore soft-deleted rolesforce-delete-roles- Permanently delete rolesassign-permissions- Attach permissions to rolesrevoke-permissions- Detach permissions from rolesmanage-roles- Full role management (grants all role permissions)
Permission Management Permissions
view-permissions- View permission listings and detailscreate-permissions- Create new permissionsedit-permissions- Update existing permissionsdelete-permissions- Delete permissionsrestore-permissions- Restore soft-deleted permissionsforce-delete-permissions- Permanently delete permissionsassign-roles- Attach roles to permissionsrevoke-roles- Detach roles from permissionsmanage-permissions- Full permission management (grants all permission permissions)
Super Admin Role
- Users with the
super-adminrole bypass all authorization checks
Custom Authorization Policies
To override the default policies with your own logic:
- Create custom policy classes:
// app/Policies/RolePolicy.php namespace App\Policies; use App\Models\User; use Spatie\Permission\Models\Role; class RolePolicy { public function before(User $user, $ability): ?bool { // Super admin bypasses all checks if ($user->hasRole('super-admin')) { return true; } return null; } public function viewAny(User $user): bool { return $user->hasPermissionTo('view-roles'); } public function create(User $user): bool { return $user->hasPermissionTo('create-roles'); } // ... other methods }
- Register your custom policies with the tool:
public function tools() { return [ (new NovaSpatieRolePermissionTool()) ->rolePolicy(App\Policies\RolePolicy::class) ->permissionPolicy(App\Policies\PermissionPolicy::class), ]; }
Testing
composer test
Development
Code Quality
Run code formatting:
composer format
Run static analysis:
composer analyse
Note: Static analysis excludes Nova-dependent files since Nova is not available during package development. These files are fully functional when Nova is installed in your application.
Troubleshooting
Common Issues and Solutions
"Class name must be a valid object or a string" Error
This error occurs when the configuration file is not properly loaded. Solutions:
- Publish the configuration file (if not using defaults):
php artisan vendor:publish --provider="Iamgerwin\NovaSpatieRolePermission\ToolServiceProvider"
php artisan config:clear
- Clear all caches:
php artisan config:clear php artisan cache:clear php artisan route:clear php artisan view:clear
Package Not Working After Installation
If the package isn't working after installation:
# Clear all caches composer dump-autoload php artisan config:clear php artisan cache:clear php artisan nova:publish # Verify installation php artisan nova-permission:verify
Missing Permissions or Roles
If permissions or roles aren't showing up:
- Check if migrations have been run:
php artisan migrate:status
- Clear the permission cache:
php artisan permission:cache-reset
- Verify your models are configured correctly:
php artisan nova-permission:verify
Authorization Not Working
If users can't access roles/permissions despite having the right permissions:
- Ensure the user has the correct permissions:
// Check in tinker php artisan tinker >>> User::find(1)->hasPermissionTo('manage-roles')
- Clear permission cache:
php artisan permission:cache-reset
- Check if super-admin role is configured:
php artisan nova-permission:verify
Verification Command
Use the verification command to diagnose installation issues:
php artisan nova-permission:verify
This command checks:
- ✓ Configuration file status
- ✓ Nova installation
- ✓ Spatie Permission installation
- ✓ Database migrations
- ✓ Model configurations
- ✓ Nova resource registrations
Getting Help
If you're still experiencing issues:
- Run the verification command and include the output in your issue report
- Check the GitHub Issues
- Review the CHANGELOG for recent changes
- Ensure you're using compatible versions (see Requirements section)
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
This package is based on the original work by vyuldashev/nova-permission and has been updated and enhanced for modern Laravel, Nova, and PHP versions.
License
The MIT License (MIT). Please see License File for more information.
iamgerwin/nova-spatie-role-permission 适用场景与选型建议
iamgerwin/nova-spatie-role-permission 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.52k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2025 年 09 月 26 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「authorization」 「nova」 「acl」 「laravel」 「roles」 「permissions」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 iamgerwin/nova-spatie-role-permission 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 iamgerwin/nova-spatie-role-permission 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 iamgerwin/nova-spatie-role-permission 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A Laravel Nova card that shows you your system information.
A Laravel Nova card.
Laravel Multiauth package
Ory-Hydra OAuth 2.0 Client Provider for The PHP League OAuth2-Client
A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.
A Laravel Nova package for publishable fields
统计信息
- 总下载量: 4.52k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-09-26