PHPackages                             mike-bronner/laravel-governor - 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. mike-bronner/laravel-governor

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

mike-bronner/laravel-governor
=============================

Managing policy and control in Laravel.

0.22.0(2mo ago)20007[3 issues](https://github.com/mike-bronner/laravel-governor/issues)[3 PRs](https://github.com/mike-bronner/laravel-governor/pulls)MITPHPPHP ^8.2CI passing

Since Sep 2Pushed 1mo ago7 watchersCompare

[ Source](https://github.com/mike-bronner/laravel-governor)[ Packagist](https://packagist.org/packages/mike-bronner/laravel-governor)[ GitHub Sponsors](https://github.com/mikebronner)[ RSS](/packages/mike-bronner-laravel-governor/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (204)Used By (0)

Governor For Laravel
====================

[](#governor-for-laravel)

[![Tests](https://github.com/mikebronner/laravel-governor/actions/workflows/tests.yml/badge.svg)](https://github.com/mikebronner/laravel-governor/actions/workflows/tests.yml)[![codecov](https://camo.githubusercontent.com/324a452467b6f83b8769b440ed9bedfe4ac1511c94c7d7eda9eb1e197b845188/68747470733a2f2f636f6465636f762e696f2f67682f6d696b6562726f6e6e65722f6c61726176656c2d676f7665726e6f722f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/mikebronner/laravel-governor)[![Latest StableVersion](https://camo.githubusercontent.com/b9adc4fb319a41279cb848afe4524f94250caf7535a29cf9930d4e5173c677d6/68747470733a2f2f706f7365722e707567782e6f72672f67656e65616c6162732f6c61726176656c2d676f7665726e6f722f762f737461626c652e706e67)](https://packagist.org/packages/genealabs/laravel-governor)[![Total Downloads](https://camo.githubusercontent.com/13c173bf166c4412987eedcb805928a5eba1cf2cf2ed67cd547b20ab8d3f1e01/68747470733a2f2f706f7365722e707567782e6f72672f67656e65616c6162732f6c61726176656c2d676f7665726e6f722f646f776e6c6f6164732e706e67)](https://packagist.org/packages/genealabs/laravel-governor)

[![Governor for Laravel](https://repository-images.githubusercontent.com/41706753/37d93d00-f1b1-11e9-9f67-067c80849466)](https://repository-images.githubusercontent.com/41706753/37d93d00-f1b1-11e9-9f67-067c80849466)

**Manage authorization with granular role-based permissions in your Laravel apps.**

[![screencast 2017-06-04 at 3 34 56 pm](https://cloud.githubusercontent.com/assets/1791050/26765962/fa085878-493b-11e7-9bb7-b4d9f88844a0.gif)](https://cloud.githubusercontent.com/assets/1791050/26765962/fa085878-493b-11e7-9bb7-b4d9f88844a0.gif)

Goal
----

[](#goal)

Provide a simple method of managing ACL in a Laravel application built on the Laravel Authorization functionality. By leveraging Laravel's native Authorization functionality there is no additional learning or implementation curve. All you need to know is Laravel, and you will know how to use Governor for Laravel.

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

[](#requirements)

LaravelPHPPackage10.x8.2+latest11.x8.2+latest12.x8.2+latest13.x8.3+latest### Additional Requirements

[](#additional-requirements)

- Bootstrap 3 (needs to be included in your layout file)
- FontAwesome 4 (needs to be included in your layout file)

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

[](#installation)

The user with the lowest primary key will be set up as the SuperAdmin. If you're starting on a new project, be sure to add an initial user now. If you already have users, you can update the role-user entry to point to your intended user, if the first user is not the intended SuperAdmin. Now let's get the package installed.

Install via composer:

```
composer require genealabs/laravel-governor
```

Implementation
--------------

[](#implementation)

1. First we need to update the database by running the migrations and data seeders:

    ```
    php artisan migrate --path="vendor/genealabs/laravel-governor/database/migrations"
    php artisan db:seed --class=LaravelGovernorDatabaseSeeder
    ```
2. If you have seeders of your own, run them now:

    ```
    php artisan db:seed
    ```
3. Next, assign permissions (this requires you have users already populated):

    ```
    php artisan db:seed --class=LaravelGovernorPermissionsTableSeeder
    ```
4. Now we need to make the assets available:

    ```
    php artisan governor:publish --assets
    ```
5. Lastly, add the Governable trait to the User model of your app:

    ```
    // [...]
    use GeneaLabs\LaravelGovernor\Traits\Governable;

    class User extends Authenticatable
    {
        use Governable;
        // [...]
    }
    ```

Upgrading
---------

[](#upgrading)

The following upgrade guides should help navigate updates with breaking changes.

### From 0.11.5+ to 0.12 \[Breaking\]

[](#from-0115-to-012-breaking)

The role\_user pivot table has replaced the composite key with a primary key, as Laravel does not fully support composite keys. Run:

```
php artisan db:seed --class="LaravelGovernorUpgradeTo0120"
```

### From 0.11 to 0.11.5 \[Breaking\]

[](#from-011-to-0115-breaking)

The primary keys of the package's tables have been renamed. (This should have been a minor version change, instead of a patch, as this was a breaking change.) Run:

```
php artisan db:seed --class="LaravelGovernorUpgradeTo0115"
```

### From 0.10 to 0.11 \[Breaking\]

[](#from-010-to-011-breaking)

The following traits have changed:

- `Governable` has been renamed to `Governing`.
- `Governed` has been renamed to `Governable`.
- the `governor_created_by` has been renamed to `governor_owned_by`. Run migrations to update your tables. ```
    php artisan db:seed --class="LaravelGovernorUpgradeTo0110"
    ```
- replace any reference in your app from `governor_created_by` to `governor_owned_by`.

### From 0.6 to Version 0.10 \[Breaking\]

[](#from-06-to-version-010-breaking)

To upgrade from version previous to `0.10.0`, first run the migrations and seeders, then run the update seeder:

```
php artisan migrate --path="vendor/genealabs/laravel-governor/database/migrations"
php artisan db:seed --class="LaravelGovernorDatabaseSeeder"
php artisan db:seed --class="LaravelGovernorUpgradeTo0100"
```

### to 0.6 \[Breaking\]

[](#to-06-breaking)

1. If you were extending `GeneaLabs\LaravelGovernor\Policies\LaravelGovernorPolicy`, change to extend `GeneaLabs\LaravelGovernor\Policies\BasePolicy`;
2. Support for version of Laravel lower than 5.5 has been dropped.

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

[](#configuration)

If you need to make any changes (see Example selection below for the default config file) to the default configuration, publish the configuration file:

```
php artisan governor:publish --config
```

and make any necessary changes. (We don't recommend publishing the config file if you don't need to make any changes.)

### Views

[](#views)

If you would like to customize the views, publish them:

```
php artisan governor:publish --views
```

and edit them in `resources\views\vendor\genealabs\laravel-governor`.

### Policies

[](#policies)

Policies are now auto-detected and automatically added to the entities list. You will no longer need to manage Entities manually. New policies will be available for role assignment when editing roles. Check out the example policy in the Examples section below. See Laravel's documentation on how to create policies and check for them in code:

**Your policies must extend LaravelGovernorPolicy in order to function with Governor.** By default you do not need to include any of the methods, as they are implemented automatically and perform checks based on reflection. However, if you need to customize anything, you are free to override any of the `before`, `create`, `edit`, `view`, `inspect`, and `remove` methods.

#### Checking Authorization

[](#checking-authorization)

To validate a user against a given policy, use one of the keywords that Governor validates against: `before`, `create`, `edit`, `view`, `inspect`, and `remove`. For example, if the desired policy to check has a class name of `BlogPostPolicy`, you would authorize your user with something like `$user->can('create', (new BlogPost))`or `$user->can('edit', $blogPost)`.

### Filter Queries To Show Ownly Allowed Items

[](#filter-queries-to-show-ownly-allowed-items)

Often it is desirable to let the user see only the items that they have access to. This was previously difficult and tedious. Using Nova as an example, you can now limit the index view as follows: ```php &lt;?php namespace App\\Nova;

```
use Laravel\Nova\Resource as NovaResource;
use Laravel\Nova\Http\Requests\NovaRequest;

abstract class Resource extends NovaResource
{
    public static function indexQuery(NovaRequest $request, $query)
    {
        $model = $query->getModel();

        if ($model
            && is_object($model)
            && method_exists($model, "filterViewAnyable")
        ) {
            $query = $model->filterViewAnyable($query);
        }

        return $query;
    }

    // ...
}
```

The available query filters are:
- `filterDeletable(Builder $query)`
- `filterUpdatable(Builder $query)`
- `filterViewable(Builder $query)`
- `filterViewAnyable(Builder $query)`

The same functionality is availabe via model scopes, as well:
- `deletable()`
- `updatable()`
- `viewable()`
- `viewAnyable()`

```

### Caching

[](#caching)

Governor can cache lookup table queries (roles, actions, entities, permissions) across requests to reduce database load. This is disabled by default.

To enable caching, publish the config file and update the `cache` section:

```
'cache' => [
    'enabled' => true,
    'ttl' => 3600, // seconds, or null for "forever"
],
```

Cache is automatically invalidated when any lookup table model is modified. Invalidation is coarse-grained: a change to any single lookup table (e.g. a role) flushes the cache for all lookup tables. This keeps the invalidation logic simple and reliable, which is appropriate given that lookup tables change infrequently.

### Tables

[](#tables)

Tables will automatically be updated with a `governor_owned_by` column that references the user that created the entry. There is no more need to run separate migrations or work around packages that have models without a created\_by property.

### Admin Views

[](#admin-views)

The easiest way to integrate Governor for Laravel into your app is to add the menu items to the relevant section of your app's menu (make sure to restrict access appropriately using the Laravel Authorization methods). The following routes can be added:

- Role Management: `genealabs.laravel-governor.roles.index`
- User-Role Assignments: `genealabs.laravel-governor.assignments.index`

For example:

```
Governor
```

### 403 Unauthorized

[](#403-unauthorized)

We recommend making a custom 403 error page to let the user know they don't have access. Otherwise the user will just see the default error message. See  for more details on how to set those up.

### Authorization API

[](#authorization-api)

You can check a user's ability to perform certain actions via a public API. It is recommended to use Laravel Passport to maintain session state between your client and your backend. Here's an example that checks if the currently logged in user can create `GeneaLabs\LaravelGovernor\Role` model records:

```
$response = $this
    ->json(
        "GET",
        route('genealabs.laravel-governor.api.user-can.show', "create"),
        [
            "model" => "GeneaLabs\LaravelGovernor\Role",
        ]
    );
```

This next example checks if the user can edit `GeneaLabs\LaravelGovernor\Role`model records:

```
$response = $this
    ->json(
        "GET",
        route('genealabs.laravel-governor.api.user-can.show', "edit"),
        [
            "model" => "GeneaLabs\LaravelGovernor\Role",
            "primary-key" => 1,
        ]
    );
```

The abilities `inspect`, `edit`, and `remove`, except `create` and `view`, require the primary key to be passed.

### Role-Check API

[](#role-check-api)

// TODO: add documentation

```
$response = $this
    ->json(
        "GET",
        route('genealabs.laravel-governor.api.user-is.show', "SuperAdmin")
    );
```

Examples
--------

[](#examples)

### Config File

[](#config-file)

```
