PHPackages                             jundayw/policy - 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. jundayw/policy

ActiveLibrary

jundayw/policy
==============

A flexible policy verification system for Laravel, supporting dynamic return of permission identifiers through model methods and providing easy integration with middleware.

v1.0.0(1mo ago)07—0%MITPHPPHP ^8.0

Since Mar 20Pushed 1mo agoCompare

[ Source](https://github.com/jundayw/policy)[ Packagist](https://packagist.org/packages/jundayw/policy)[ Docs](https://github.com/jundayw/policy)[ RSS](/packages/jundayw-policy/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

Policy
======

[](#policy)

A flexible policy verification system for Laravel, supporting dynamic return of permission identifiers through model methods and providing easy integration with middleware.

[中文](./README_CN.md) | English

[![GitHub Tag](https://camo.githubusercontent.com/1672d21e95ed5d9ebe9cb237e6a0f98af03a2e619498c7b8205bd73da29cc7bd/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f7461672f6a756e646179772f706f6c696379)](https://github.com/jundayw/policy/tags)[![Total Downloads](https://camo.githubusercontent.com/7abd31ef45bf777befaeffebde5d0f9d7fdcb83199e006e6c697965fd8c831a3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a756e646179772f706f6c6963793f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jundayw/policy)[![Packagist Version](https://camo.githubusercontent.com/0c75b85980186ea188e435049856438c02ee02998c0059892e0e90f3549a10db/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a756e646179772f706f6c696379)](https://packagist.org/packages/jundayw/policy)[![Packagist PHP Version Support](https://camo.githubusercontent.com/f84723322d1f4b61fe772736d67e7513b68ec25047104c00e8fe9d0400f00170/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6a756e646179772f706f6c696379)](https://github.com/jundayw/policy)[![Packagist License](https://camo.githubusercontent.com/207d4d6eaad4ce87b1b1cfac3114ca44d2ddeab808912da526913108cd16c96d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6a756e646179772f706f6c696379)](https://github.com/jundayw/policy)

 Table of Contents1. [Installation](#installation)
2. [Usage](#usage)
3. [Contributing](#contributing)
4. [Contributors](#contributors)
5. [License](#license)

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

[](#installation)

You can install the package via [Composer](https://getcomposer.org):

```
composer require jundayw/policy
```

\[[back to top](#readme-top)\]

Usage
-----

[](#usage)

### Model Preparation

[](#model-preparation)

The model to be verified (e.g., `App\Models\User`) must implement the `Jundayw\Policy\Contracts\Policeable` interface and use the `Jundayw\Policy\Concerns\HasPolicy` trait. Also, implement the `getPolicies(string $ability, array $arguments = []): array` method to return an array of permission identifiers that the current user possesses.

```
namespace App\Models;

use Jundayw\Policy\Concerns\HasPolicy;
use Jundayw\Policy\Contracts\Policeable;

class User extends Authenticatable implements Policeable
{
    use HasPolicy;

    public function getPolicies(string $ability, array $arguments = []): array
    {
        // Here you can obtain the user's permission list from the database, cache, etc.
        return [
            'backend.module.create',
            'backend.module.edit',
            'backend.policy.list',
            'backend.policy.create',
            'backend.policy.update',
            'backend.policy.destroy',
            'backend.role.*',
            'backend.*.*',
        ];
    }
}
```

### Using Built-in Middleware

[](#using-built-in-middleware)

The package provides a `policy` middleware that you can use directly in controllers or routes for permission verification.

**In the controller constructor:**

```
class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('policy');
    }
}
```

**In route definitions:**

```
Route::middleware('policy')->group(function () {
    Route::get('/users', [UserController::class, 'index']);
    Route::post('/users', [UserController::class, 'store']);
    // ...
});
```

When a user is unauthorized, the built-in middleware throws a `Jundayw\Policy\Exceptions\PolicyException`. You should handle this exception according to your application's needs (e.g., return a 403 page or JSON response).

### Custom Middleware

[](#custom-middleware)

If you need more control (e.g., custom rules for generating permission identifiers), you can create your own middleware:

```
use Jundayw\Policy\Policy;
use Jundayw\Policy\Exceptions\PolicyException;

class CustomPolicyMiddleware
{
    public function handle($request, $next)
    {
        // Generate a permission identifier based on the request, e.g., "admin.user.update"
        $policy = $this->determinePolicy($request);

        if ($request->user()->can($policy, [Policy::class])) {
            return $next($request);
        }

        // Custom unauthorized behavior
        throw new PolicyException('Unauthorized', 403);
    }

    protected function determinePolicy($request)
    {
        // Example: dynamically construct a permission string from the route or request
        return $request->route()->getName();
    }
}
```

### Custom Permission Identifier

[](#custom-permission-identifier)

Create a custom rule class for generating permission identifiers:

```
use Illuminate\Http\Request;
use Jundayw\Policy\Contracts\CanPoliceable;

class CustomPoliceable implements CanPoliceable
{
    public function __invoke(Request $request): mixed
    {
        if (app()->runningInConsole()) {
            return null;
        }

        return $request->path();
    }
}
```

Register it in the container:

```
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Jundayw\Policy\Contracts\CanPoliceable;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        $this->app->bind(CanPoliceable::class, function () {
            return new CustomPoliceable;
        });
    }
}
```

### Debug Mode

[](#debug-mode)

You can enable or disable permission verification by publishing the configuration file, which is useful for temporarily bypassing permission checks in development or testing environments.

Publish the configuration file:

```
php artisan vendor:publish --tag=policy-config
```

The configuration file will be located at `config/policy.php` with the following content:

```
