A Laravel package to easily generate permission classes with enums using Models *** This package uses Spatie/Permissions under the hood ***
- PHP 8.1 or higher
- Laravel 10.0 or higher
composer require althinect/enum-permission
Publish the configuration file:
php artisan vendor:publish --tag="enum-permission-config"
The configuration file will be published to config/enum-permission.php
.
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
]
];
# 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
# Sync all permissions
php artisan permission:sync
# Clean existing permissions before sync
php artisan permission:sync --clean
// In your policies
public function view(User $user, Post $post): bool
{
return $user->hasPermissionTo(PostPermission::VIEW);
}
After generation, your files will be organized as follows:
app/
├── Models/
│ └── User.php
├── Permissions/
│ └── UserPermission.php
└── Policies/
└── UserPolicy.php
permission:make {model?} {--P|policy}
- Generate permission enumspermission:sync {--C|clean}
- Sync permissions to database
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';
}
use App\Permissions\UserPermission;
class UserPolicy
{
public function view(User $user, User $model): bool
{
return $user->hasPermissionTo(UserPermission::VIEW);
}
}
Contributions are welcome! Please feel free to submit a Pull Request.
This package is open-source software licensed under the MIT license.