althinect / enum-permission
This package is to create permissions with enums
Fund package maintenance!
Althinect
Requires
- php: ^8.2
- illuminate/contracts: ^10.0||^11.0
- laravel/prompts: ^0.1.23
- spatie/laravel-package-tools: ^1.16
- spatie/laravel-permission: ^6.0
Requires (Dev)
- larastan/larastan: ^2.9
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.1.1||^7.10.0
- orchestra/testbench: ^9.0.0||^8.22.0
- pestphp/pest: ^2.34
- pestphp/pest-plugin-arch: ^2.7
- pestphp/pest-plugin-laravel: ^2.3
- phpstan/extension-installer: ^1.3
- phpstan/phpstan-deprecation-rules: ^1.1
- phpstan/phpstan-phpunit: ^1.3
README
A Laravel package that generates and manages permissions using PHP enums, making permission handling more type-safe and maintainable.
Requirements
- PHP 8.1 or higher
- Laravel 10.0 or higher
Installation
composer require althinect/enum-permission
Configuration
Publish the configuration file:
php artisan vendor:publish --tag="enum-permission-config"
The configuration file will be published to config/enum-permission.php
.
Configuration Options
return [ 'models_path' => 'Models', // Path to your models 'user_model' => \App\Models\User::class, // Your User model 'permissions' => [ [ 'method' => 'viewAny', 'arguments' => ['User $user'], 'enum_case' => 'VIEW_ANY', 'enum_value' => '{{modelName}}.viewAny' ], // ... other permissions ] ];
Usage
Generating Permission Enums
# Generate for a specific model php artisan permission:make User # Generate with policy php artisan permission:make User --policy # Interactive selection of models php artisan permission:make
Syncing Permissions to Database
# Sync all permissions php artisan permission:sync # Clean existing permissions before sync php artisan permission:sync --clean
Using Generated Permissions
// In your policies public function view(User $user, Post $post): bool { return $user->hasPermissionTo(PostPermission::VIEW); }
Directory Structure
After generation, your files will be organized as follows:
app/
├── Models/
│ └── User.php
├── Permissions/
│ └── UserPermission.php
└── Policies/
└── UserPolicy.php
Available Commands
permission:make {model?} {--P|policy}
- Generate permission enumspermission:sync {--C|clean}
- Sync permissions to database
Examples
Generated Permission Enum
namespace App\Permissions; enum UserPermission: string { case VIEW_ANY = 'User.viewAny'; case VIEW = 'User.view'; case CREATE = 'User.create'; case UPDATE = 'User.update'; case DELETE = 'User.delete'; case RESTORE = 'User.restore'; case FORCE_DELETE = 'User.forceDelete'; }
Using with Policies
use App\Permissions\UserPermission; class UserPolicy { public function view(User $user, User $model): bool { return $user->hasPermissionTo(UserPermission::VIEW); } }
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This package is open-source software licensed under the MIT license.