PHPackages                             althinect/enum-permission - 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. althinect/enum-permission

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

althinect/enum-permission
=========================

This package is to create permissions with enums

v1.1(2d ago)1242[1 PRs](https://github.com/Althinect/enum-permission/pulls)MITPHPPHP ^8.2CI failing

Since Dec 21Pushed yesterday2 watchersCompare

[ Source](https://github.com/Althinect/enum-permission)[ Packagist](https://packagist.org/packages/althinect/enum-permission)[ Docs](https://github.com/althinect/enum-permission)[ GitHub Sponsors](https://github.com/Althinect)[ RSS](/packages/althinect-enum-permission/feed)WikiDiscussions main Synced today

READMEChangelog (10)Dependencies (13)Versions (23)Used By (0)

Laravel Enum Permissions
========================

[](#laravel-enum-permissions)

[![Latest Version on Packagist](https://camo.githubusercontent.com/20b04fb230bdbc1e016b4829f4755a2b904bc52ca09e31e4b84ad154b04a9c19/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616c7468696e6563742f656e756d2d7065726d697373696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/althinect/enum-permission)[![Total Downloads](https://camo.githubusercontent.com/fadfa9012dc27d4ee43a8dfa4e50fadc163278a5728452ff9a084679e2e9463c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f616c7468696e6563742f656e756d2d7065726d697373696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/althinect/enum-permission)

A Laravel package to easily manage Permissions with Enums and sync these permissions to your database. This package is built on top of Spatie's Laravel-Permission package, providing an enum-based approach to permission management. It's fully configured via the config file located at `config/enum-permission.php`.

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 10.0 to 13.x
- Spatie/Laravel-Permission package

Installation
------------

[](#installation)

```
composer require althinect/enum-permission
```

This package automatically installs Spatie's Laravel-Permission package as a dependency, so you don't need to require it separately.

### Spatie configs

[](#spatie-configs)

You will need to run the migrations and add the necessary configs according to the Spatie Permissions documentation

After installation, publish the configuration file:

```
php artisan vendor:publish --tag="enum-permission-config"
```

Then run the migrations to set up all required tables including the permissions tables from Spatie and the group column added by this package:

```
php artisan migrate
```

Configuration
-------------

[](#configuration)

The configuration file will be published to `config/enum-permission.php`. Customize your permissions, models path, and other options there.

### Configuration Options

[](#configuration-options)

```
return [
    // Path to your models
    'models_path' => 'app/Models',

    // Your User model
    'user_model' => \App\Models\User::class,

    // Classes that models should extend for discovery
    'model_super_classes' => [
        'Illuminate\Database\Eloquent\Model',
        'Illuminate\Foundation\Auth\User',
    ],

    // Permission definitions for policy methods
    'permissions' => [
        [
            'method' => 'viewAny',
            'arguments' => ['{{userModelName}} $user'],
            'enum_case' => 'VIEW_ANY',
            'enum_value' => '{{modelName}}.view-any'
        ],
        // ... other permissions
    ],

    // Auth guards to create permissions for
    'guards' => [
        'web',
        'api',
    ],

    // Whether to sync permission groups
    'sync_permission_group' => false,
];
```

Migrations
----------

[](#migrations)

This package relies on the database tables created by the Spatie Laravel-Permission package and automatically adds a 'group' column to the permissions table for better organization.

When you install this package and run migrations, two things happen:

1. The Spatie migrations create the core permission tables:

    - `permissions` - Stores all permissions
    - `roles` - Stores all roles
    - `model_has_permissions` - Maps permissions to users or other models
    - `model_has_roles` - Maps roles to users or other models
    - `role_has_permissions` - Maps permissions to roles
2. This package adds its own migration to enhance the permissions table:

    - Adds a `group` column to the `permissions` table
    - Creates an index on the `group` column for faster queries

The `group` column is used when `sync_permission_group` is enabled in the config, allowing permissions to be organized by model name, which is especially useful for UI-based permission management systems.

Usage
-----

[](#usage)

### Generating Permission Enums

[](#generating-permission-enums)

The `permission:make` command generates permission enums (and policies if requested) for your models.

```
# Generate for a specific model
php artisan permission:make User

# Generate with policy
php artisan permission:make User --policy

# Skip confirmation prompts (useful for CI/CD)
php artisan permission:make User --force

# Interactive selection of models
php artisan permission:make
```

### Syncing Permissions to Database

[](#syncing-permissions-to-database)

The `permission:sync` command scans for permission enums and syncs them to the database.

```
# Sync all permissions
php artisan permission:sync

# Clean existing permissions before sync
php artisan permission:sync --clean

# Skip confirmation prompts (useful for CI/CD)
php artisan permission:sync --force

# Specify a custom path to scan for permissions
php artisan permission:sync --path=app/Domain/Auth/Permissions
```

### Using Generated Permissions

[](#using-generated-permissions)

```
// In your controllers or services
if ($user->hasPermissionTo(PostPermission::CREATE)) {
    // User can create posts
}

// In your policies
public function view(User $user, Post $post): bool
{
    return $user->hasPermissionTo(PostPermission::VIEW);
}
```

Directory Structure
-------------------

[](#directory-structure)

After generation, your files will be organized as follows:

```
app/
├── Models/
│   └── User.php
├── Permissions/  (mirrors your Models directory structure)
│   └── UserPermission.php
└── Policies/
    └── UserPolicy.php

```

If your models use domain-driven structure, permission enums will follow the same structure:

```
app/
├── Domain/
│   └── Blog/
│       ├── Models/
│       │   └── Post.php
│       └── Permissions/
│           └── PostPermission.php
└── Policies/
    └── PostPolicy.php

```

Available Commands
------------------

[](#available-commands)

- `permission:make {modelName?} {--P|policy} {--force}` - Generate permission enums and optional policies
- `permission:sync {--C|clean} {--path=} {--force}` - Sync permissions to database

Examples
--------

[](#examples)

### Generated Permission Enum

[](#generated-permission-enum)

```
namespace App\Permissions;

use Althinect\EnumPermission\Concerns\HasPermissionGroup;

enum UserPermission: string
{
    use HasPermissionGroup;

    case VIEW_ANY = 'User.view-any';
    case VIEW = 'User.view';
    case CREATE = 'User.create';
    case UPDATE = 'User.update';
    case DELETE = 'User.delete';
    case RESTORE = 'User.restore';
    case FORCE_DELETE = 'User.force-delete';
}
```

### Generated Policy

[](#generated-policy)

```
namespace App\Policies;

use App\Models\User;
use App\Permissions\UserPermission;

class UserPolicy
{
    public function viewAny(User $user): bool
    {
        return $user->hasPermissionTo(UserPermission::VIEW_ANY);
    }

    public function view(User $user, User $model): bool
    {
        return $user->hasPermissionTo(UserPermission::VIEW);
    }

    // Additional methods for create, update, delete, etc.
}
```

### Permission Groups

[](#permission-groups)

When `sync_permission_group` is enabled in the config, permissions will be grouped by model name, which is helpful for UI-based permission management:

```
// In UserPermission.php
public static function getPermissionGroup(): string
{
    return str_replace('Permission', '', class_basename(static::class)); // Returns "User"
}
```

This feature uses the `group` column added to the `permissions` table by this package's migration. The permissions are grouped automatically during the sync process:

```
// Example of how permissions are stored with groups
[
    'name' => 'User.view',
    'guard_name' => 'web',
    'group' => 'User' //
