PHPackages                             anggarasaja/laravel-permission-mongodb - 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. [Database &amp; ORM](/categories/database)
4. /
5. anggarasaja/laravel-permission-mongodb

ActiveLibrary[Database &amp; ORM](/categories/database)

anggarasaja/laravel-permission-mongodb
======================================

Permission handling for Laravel 5.2 and up using mongodb

v1.8.0(7y ago)08MITPHPPHP &gt;=7.0

Since Aug 21Pushed 7y ago1 watchersCompare

[ Source](https://github.com/anggarasaja/laravel-permission-mongodb)[ Packagist](https://packagist.org/packages/anggarasaja/laravel-permission-mongodb)[ Docs](https://github.com/mostafamaklad/laravel-permission-mongodb)[ RSS](/packages/anggarasaja-laravel-permission-mongodb/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (9)Versions (32)Used By (0)

laravel-permission-mongodb
==========================

[](#laravel-permission-mongodb)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d6355a37c7c21679b19639acb06145f18f799a0ecd554324db893335e680b347/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616e676761726173616a612f6c61726176656c2d7065726d697373696f6e2d6d6f6e676f64622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/anggarasaja/laravel-permission-mongodb)[![Software License](https://camo.githubusercontent.com/0ab8f070d94182e25a302fd1d1487ac4b99274b4189d497350a12ce65c25d3df/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f616e676761726173616a612f6c61726176656c2d7065726d697373696f6e2d6d6f6e676f64622e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/977bf295b9d6e52c963b286419a30809df14c614d65ab824bbae66f7e8930447/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f616e676761726173616a612f6c61726176656c2d7065726d697373696f6e2d6d6f6e676f64622f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/anggarasaja/laravel-permission-mongodb)[![Scrutinizer](https://camo.githubusercontent.com/0f424cd5b1e0a8ce64c6ad2c16824711c1c0927442097ac86dee2d354e3f021f/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f616e676761726173616a612f6c61726176656c2d7065726d697373696f6e2d6d6f6e676f64622e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/anggarasaja/laravel-permission-mongodb)[![Maintainability](https://camo.githubusercontent.com/0db894e010bce559aa26eec3c928bda7953822f09aef8bf5c02b34159e5a0df9/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f30303563333634346132646236623336343531342f6d61696e7461696e6162696c697479)](https://codeclimate.com/github/anggarasaja/laravel-permission-mongodb/maintainability)[![Codacy Badge](https://camo.githubusercontent.com/6a6aa2c5248050abdeda22668eb623bf2a843e41df62b37c433d2552e2b05727/68747470733a2f2f6170692e636f646163792e636f6d2f70726f6a6563742f62616467652f47726164652f3131363230323833623138393435653262656237376535396464633930363234)](https://www.codacy.com/app/anggarasaja/laravel-permission-mongodb?utm_source=github.com&utm_medium=referral&utm_content=anggarasaja/laravel-permission-mongodb&utm_campaign=Badge_Grade)[![StyleCI](https://camo.githubusercontent.com/5420f75952f0d4d9374e001e4ec48d37d8ad4199d91c2695215804c4684c1b3b/68747470733a2f2f7374796c6563692e696f2f7265706f732f3130303839343036322f736869656c643f7374796c653d666c61742d737175617265)](https://styleci.io/repos/100894062)[![Coverage Status](https://camo.githubusercontent.com/a394fa076965af09e2d4e5b4f024040b94379645a768f553a3b001eae37a6fa8/68747470733a2f2f696d672e736869656c64732e696f2f636f766572616c6c732f616e676761726173616a612f6c61726176656c2d7065726d697373696f6e2d6d6f6e676f64622e7376673f7374796c653d666c61742d737175617265)](https://coveralls.io/github/anggarasaja/laravel-permission-mongodb)[![Dependency Status](https://camo.githubusercontent.com/11e851986a3b78d3d23c8ac3fc6be3758f5f87b6a0f5803cc25955ca6bbdb9f2/68747470733a2f2f696d672e736869656c64732e696f2f67656d6e617369756d2f616e676761726173616a612f6c61726176656c2d7065726d697373696f6e2d6d6f6e676f64622e7376673f7374796c653d666c61742d737175617265)](https://gemnasium.com/github.com/anggarasaja/laravel-permission-mongodb)[![Total Downloads](https://camo.githubusercontent.com/f181f5b5423222e6768bccc4fac8e2f9760e46b31f422aa5421f2c09bf18e1ad/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f616e676761726173616a612f6c61726176656c2d7065726d697373696f6e2d6d6f6e676f64622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/anggarasaja/laravel-permission-mongodb)

This package allows you to manage user permissions and roles in a database. It is inspired from [laravel-permission](https://github.com/spatie/laravel-permission). Same code same every thing but it is compatible with [laravel-mongodb](https://github.com/jenssegers/laravel-mongodb)

Once installed you can do stuff like this:

```
// Adding permissions to a user
$user->givePermissionTo('edit articles');

// Adding permissions via a role
$user->assignRole('writer');

$role->givePermissionTo('edit articles');
```

If you're using multiple guards we've got you covered as well. Every guard will have its own set of permissions and roles that can be assigned to the guard's users. Read about it in the [using multiple guards](#using-multiple-guards) section of the readme.

Because all permissions will be registered on [Laravel's gate](https://laravel.com/docs/5.5/authorization), you can test if a user has a permission with Laravel's default `can` function:

```
$user->can('edit articles');
```

Table of contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
    - [Laravel](#laravel)
    - [Lumen](#lumen)
- [Usage](#usage)
    - [Using "direct" permissions](#using-direct-permissions)
    - [Using permissions via roles](#using-permissions-via-roles)
    - [Using Blade directives](#using-blade-directives)
- [Using multiple guards](#using-multiple-guards)
    - [Using permissions and roles with multiple guards](#using-permissions-and-roles-with-multiple-guards)
    - [Assigning permissions and roles to guard users](#assigning-permissions-and-roles-to-guard-users)
    - [Using blade directives with multiple guards](#using-blade-directives-with-multiple-guards)
- [Using a middleware](#using-a-middleware)
- [Using artisan commands](#using-artisan-commands)
- [Unit Testing](#unit-testing)
- [Database Seeding](#database-seeding)
- [Extending](#extending)
- [Cache](#cache)
    - [Manual cache reset](#manual-cache-reset)
    - [Cache Identifier](#cache-identifier)
- [Need a UI?](#need-a-ui)
- [Change log](#change-log)
- [Testing](#testing)
- [Contributing](#contributing)
- [Security](#security)
- [Credits](#credits)
- [License](#license)

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

[](#installation)

### Laravel

[](#laravel)

This package can be used in Laravel 5.2 and up.

You can install the package via composer:

```
composer require anggarasaja/laravel-permission-mongodb
```

In Laravel 5.5 the service provider will automatically get registered. In older versions of the framework just add the service provider in `config/app.php` file:

```
'providers' => [
    // ...
    Anggarasaja\Permission\PermissionServiceProvider::class,
];
```

You can publish the config file with:

```
php artisan vendor:publish --provider="Anggarasaja\Permission\PermissionServiceProvider" --tag="config"
```

When published, the [`config/permission.php`](https://github.com/anggarasaja/laravel-permission-mongodb/blob/master/config/permission.php) config file contains:

```
return [

    'models' => [

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * Moloquent model should be used to retrieve your permissions. Of course, it
         * is often just the "Permission" model but you may use whatever you like.
         *
         * The model you want to use as a Permission model needs to implement the
         * `a\Permission\Contracts\Permission` contract.
         */

        'permission' => Anggarasaja\Permission\Models\Permission::class,

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * Moloquent model should be used to retrieve your roles. Of course, it
         * is often just the "Role" model but you may use whatever you like.
         *
         * The model you want to use as a Role model needs to implement the
         * `Anggarasaja\Permission\Contracts\Role` contract.
         */

        'role' => Anggarasaja\Permission\Models\Role::class,

    ],

    'collection_names' => [

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your roles. We have chosen a basic
         * default value but you may easily change it to any table you like.
         */

        'roles' => 'roles',

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your permissions. We have chosen a basic
         * default value but you may easily change it to any table you like.
         */

        'permissions' => 'permissions',
    ],

    /*
     * By default all permissions will be cached for 24 hours unless a permission or
     * role is updated. Then the cache will be flushed immediately.
     */

    'cache_expiration_time' => 60 * 24,

    /*
     * By default we'll make an entry in the application log when the permissions
     * could not be loaded. Normally this only occurs while installing the packages.
     *
     * If for some reason you want to disable that logging, set this value to false.
     */

    'log_registration_exception' => true,

    /*
     * When set to true, the required permission/role names are added to the exception
     * message. This could be considered an information leak in some contexts, so
     * the default setting is false here for optimum safety.
     */

    'display_permission_in_exception' => false,
];
```

### Lumen

[](#lumen)

You can install the package via Composer:

```
composer require anggarasaja/laravel-permission-mongodb
```

Copy the required files:

```
cp vendor/anggarasaja/laravel-permission-mongodb/config/permission.php config/permission.php
```

You will also need to create another configuration file at `config/auth.php`. Get it on the Laravel repository or just run the following command:

```
curl -Ls https://raw.githubusercontent.com/laravel/lumen-framework/5.5/config/auth.php -o config/auth.php
```

Then, in `bootstrap/app.php`, register the middlewares:

```
$app->routeMiddleware([
    'auth'       => App\Http\Middleware\Authenticate::class,
    'permission' => Anggarasaja\Permission\Middlewares\PermissionMiddleware::class,
    'role'       => Anggarasaja\Permission\Middlewares\RoleMiddleware::class,
]);
```

As well as the configuration and the service provider:

```
$app->configure('permission');
$app->register(Anggarasaja\Permission\PermissionServiceProvider::class);
```

Usage
-----

[](#usage)

First, add the `Anggarasaja\Permission\Traits\HasRoles` trait to your `User` model(s):

```
use Illuminate\Auth\Authenticatable;
use Jenssegers\Mongodb\Eloquent\Model as Model;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Anggarasaja\Permission\Traits\HasRoles;

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable, HasRoles;

    // ...
}
```

> Note: that if you need to use `HasRoles` trait with another model ex.`Page` you will also need to add `protected $guard_name = 'web';` as well to that model or you would get an error

```
use Jenssegers\Mongodb\Eloquent\Model as Model;
use Anggarasaja\Permission\Traits\HasRoles;

class Page extends Model
{
    use HasRoles;

    protected $guard_name = 'web'; // or whatever guard you want to use

    // ...
}
```

This package allows for users to be associated with permissions and roles. Every role is associated with multiple permissions. A `Role` and a `Permission` are regular Moloquent models. They require a `name` and can be created like this:

```
use Anggarasaja\Permission\Models\Role;
use Anggarasaja\Permission\Models\Permission;

$role = Role::create(['name' => 'writer']);
$permission = Permission::create(['name' => 'edit articles']);
```

A permission can be assigned to a role using 1 of these methods:

```
$role->givePermissionTo($permission);
$permission->assignRole($role);
```

Multiple permissions can be synced to a role using 1 of these methods:

```
$role->syncPermissions($permissions);
$permission->syncRoles($roles);
```

A permission can be removed from a role using 1 of these methods:

```
$role->revokePermissionTo($permission);
$permission->removeRole($role);
```

If you're using multiple guards the `guard_name` attribute needs to be set as well. Read about it in the [using multiple guards](#using-multiple-guards) section of the readme.

The `HasRoles` trait adds Moloquent relationships to your models, which can be accessed directly or used as a base query:

```
// get a list of all permissions directly assigned to the user
$permissions = $user->permissions; // Returns a collection

// get all permissions inherited by the user via roles
$permissions = $user->getAllPermissions(); // Returns a collection

// get all permissions names
$permissions = $user->getPermissionNames(); // Returns a collection

// get a collection of all defined roles
$roles = $user->roles->pluck('name'); // Returns a collection

// get all role names
$roles = $user->getRoleNames() // Returns a collection;
```

The `HasRoles` trait also adds a `role` scope to your models to scope the query to certain roles or permissions:

```
$users = User::role('writer')->get(); // Returns only users with the role 'writer'
$users = User::permission('edit articles')->get(); // Returns only users with the permission 'edit articles'
```

The scope can accept a string, a `\Anggarasaja\Permission\Models\Role` object, a `\Anggarasaja\Permission\Models\Permission` object or an `\Illuminate\Support\Collection` object.

### Using "direct" permissions

[](#using-direct-permissions)

A permission can be given to any user with the `HasRoles` trait:

```
$user->givePermissionTo('edit articles');

// You can also give multiple permission at once
$user->givePermissionTo('edit articles', 'delete articles');

// You may also pass an array
$user->givePermissionTo(['edit articles', 'delete articles']);
```

A permission can be revoked from a user:

```
$user->revokePermissionTo('edit articles');
```

Or revoke &amp; add new permissions in one go:

```
$user->syncPermissions(['edit articles', 'delete articles']);
```

You can test if a user has a permission:

```
$user->hasPermissionTo('edit articles');
```

...or if a user has multiple permissions:

```
$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);
```

Saved permissions will be registered with the `Illuminate\Auth\Access\Gate` class for the default guard. So you can test if a user has a permission with Laravel's default `can` function:

```
$user->can('edit articles');
```

### Using permissions via roles

[](#using-permissions-via-roles)

A role can be assigned to any user:

```
$user->assignRole('writer');

// You can also assign multiple roles at once
$user->assignRole('writer', 'admin');
// or as an array
$user->assignRole(['writer', 'admin']);
```

A role can be removed from a user:

```
$user->removeRole('writer');
```

Roles can also be synced:

```
// All current roles will be removed from the user and replaced by the array given
$user->syncRoles(['writer', 'admin']);
```

You can determine if a user has a certain role:

```
$user->hasRole('writer');
```

You can also determine if a user has any of a given list of roles:

```
$user->hasAnyRole(Role::all());
```

You can also determine if a user has all of a given list of roles:

```
$user->hasAllRoles(Role::all());
```

The `assignRole`, `hasRole`, `hasAnyRole`, `hasAllRoles` and `removeRole` functions can accept a string, a `\Anggarasaja\Permission\Models\Role` object or an `\Illuminate\Support\Collection` object.

A permission can be given to a role:

```
$role->givePermissionTo('edit articles');
```

You can determine if a role has a certain permission:

```
$role->hasPermissionTo('edit articles');
```

A permission can be revoked from a role:

```
$role->revokePermissionTo('edit articles');
```

The `givePermissionTo` and `revokePermissionTo` functions can accept a string or a `Anggarasaja\Permission\Models\Permission` object.

Permissions are inherited from roles automatically. Additionally, individual permissions can be assigned to the user too.

For instance:

```
$role = Role::findByName('writer');
$role->givePermissionTo('edit articles');

$user->assignRole('writer');

$user->givePermissionTo('delete articles');
```

In the above example, a role is given permission to edit articles and this role is assigned to a user. Now the user can edit articles and additionally delete articles. The permission of `delete articles` is the user's direct permission because it is assigned directly to them. When we call `$user->hasDirectPermission('delete articles')` it returns `true`, but `false` for `$user->hasDirectPermission('edit articles')`.

This method is useful if one builds a form for setting permissions for roles and users in an application and wants to restrict or change inherited permissions of roles of the user, i.e. allowing to change only direct permissions of the user.

You can list all of these permissions:

```
// Direct permissions
$user->getDirectPermissions() // Or $user->permissions;

// Permissions inherited from the user's roles
$user->getPermissionsViaRoles();

// All permissions which apply on the user (inherited and direct)
$user->getAllPermissions();
```

All these responses are collections of `Anggarasaja\Permission\Models\Permission` objects.

If we follow the previous example, the first response will be a collection with the `delete article` permission, the second will be a collection with the `edit article` permission and the third will contain both.

### Using Blade directives

[](#using-blade-directives)

This package also adds Blade directives to verify whether the currently logged in user has all or any of a given list of roles.

Optionally you can pass in the `guard` that the check will be performed on as a second argument.

#### Blade and Roles

[](#blade-and-roles)

Test for a specific role:

```
@role('writer')
    I am a writer!
@else
    I am not a writer...
@endrole
```

is the same as

```
@hasrole('writer')
    I am a writer!
@else
    I am not a writer...
@endhasrole
```

Test for any role in a list:

```
@hasanyrole(Role::all())
    I have one or more of these roles!
@else
    I have none of these roles...
@endhasanyrole
// or
@hasanyrole('writer|admin')
    I am either a writer or an admin or both!
@else
    I have none of these roles...
@endhasanyrole
```

Test for all roles:

```
@hasallroles(Role::all())
    I have all of these roles!
@else
    I do not have all of these roles...
@endhasallroles
// or
@hasallroles('writer|admin')
    I am both a writer and an admin!
@else
    I do not have all of these roles...
@endhasallroles
```

#### Blade and Permissions

[](#blade-and-permissions)

This package doesn't add any permission-specific Blade directives. Instead, use Laravel's native `@can` directive to check if a user has a certain permission.

```
@can('edit articles')
  //
@endcan
```

or

```
@if(auth()->user()->can('edit articles') && $some_other_condition)
  //
@endif
```

Using multiple guards
---------------------

[](#using-multiple-guards)

When using the default Laravel auth configuration all of the above methods will work out of the box, no extra configuration required.

However when using multiple guards they will act like namespaces for your permissions and roles. Meaning every guard has its own set of permissions and roles that can be assigned to their user model.

### Using permissions and roles with multiple guards

[](#using-permissions-and-roles-with-multiple-guards)

By default the default guard (`config('auth.defaults.guard')`) will be used as the guard for new permissions and roles. When creating permissions and roles for specific guards you'll have to specify their `guard_name` on the model:

```
// Create a superadmin role for the admin users
$role = Role::create(['guard_name' => 'admin', 'name' => 'superadmin']);

// Define a `publish articles` permission for the admin users belonging to the admin guard
$permission = Permission::create(['guard_name' => 'admin', 'name' => 'publish articles']);

// Define a *different* `publish articles` permission for the regular users belonging to the web guard
$permission = Permission::create(['guard_name' => 'web', 'name' => 'publish articles']);
```

To check if a user has permission for a specific guard:

```
$user->hasPermissionTo('publish articles', 'admin');
```

### Assigning permissions and roles to guard users

[](#assigning-permissions-and-roles-to-guard-users)

You can use the same methods to assign permissions and roles to users as described above in [using permissions via roles](#using-permissions-via-roles). Just make sure the `guard_name` on the permission or role matches the guard of the user, otherwise a `GuardDoesNotMatch` exception will be thrown.

### Using blade directives with multiple guards

[](#using-blade-directives-with-multiple-guards)

You can use all of the blade directives listed in [using blade directives](#using-blade-directives) by passing in the guard you wish to use as the second argument to the directive:

```
@role('super-admin', 'admin')
    I am a super-admin!
@else
    I am not a super-admin...
@endrole
```

Using a middleware
------------------

[](#using-a-middleware)

This package comes with `RoleMiddleware` and `PermissionMiddleware` middleware. You can add them inside your `app/Http/Kernel.php` file.

```
protected $routeMiddleware = [
    // ...
    'role' => \Anggarasaja\Permission\Middlewares\RoleMiddleware::class,
    'permission' => \Anggarasaja\Permission\Middlewares\PermissionMiddleware::class,
];
```

Then you can protect your routes using middleware rules:

```
Route::group(['middleware' => ['role:super-admin']], function () {
    //
});

Route::group(['middleware' => ['permission:publish articles']], function () {
    //
});

Route::group(['middleware' => ['role:super-admin','permission:publish articles']], function () {
    //
});
```

You can protect your controllers similarly, by setting desired middleware in the constructor:

```
public function __construct()
{
    $this->middleware(['role:super-admin','permission:publish articles|edit articles']);
}
```

You can add something in Laravel exception handler:

```
public function render($request, Exception $exception)
{
    if ($exception instanceof \Anggarasaja\Permission\Exceptions\UnauthorizedException) {
        // Code here ...
    }

    return parent::render($request, $exception);
}
```

Using artisan commands
----------------------

[](#using-artisan-commands)

You can create a role or permission from a console with artisan commands.

```
php artisan permission:create-role writer
```

```
php artisan permission:create-permission 'edit articles'
```

When creating permissions and roles for specific guards you can specify the guard names as a second argument:

```
php artisan permission:create-role writer web
```

```
php artisan permission:create-permission 'edit articles' web
```

Unit Testing
------------

[](#unit-testing)

In your application's tests, if you are not seeding roles and permissions as part of your test `setUp()` then you may run into a chicken/egg situation where roles and permissions aren't registered with the gate (because your tests create them after that gate registration is done). Working around this is simple: In your tests simply add a `setUp()` instruction to re-register the permissions, like this:

```
public function setUp()
{
    // first include all the normal setUp operations
    parent::setUp();

    // now re-register all the roles and permissions
    $this->app->make(\Anggarasaja\Permission\PermissionRegistrar::class)->registerPermissions();
}
```

Database Seeding
----------------

[](#database-seeding)

Two notes about Database Seeding:

1. It is best to flush the `anggarasaja.permission.cache` before seeding, to avoid cache conflict errors. This can be done from an Artisan command (see Troubleshooting: Cache section, later) or directly in a seeder class (see example below).
2. Here's a sample seeder, which clears the cache, creates permissions, and then assigns permissions to roles:

```
use Illuminate\Database\Seeder;
use Anggarasaja\Permission\Models\Role;
use Anggarasaja\Permission\Models\Permission;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // Reset cached roles and permissions
        app()['cache']->forget('anggarasaja.permission.cache');

        // create permissions
        Permission::firstOrCreate(['name' => 'edit articles']);
        Permission::firstOrCreate(['name' => 'delete articles']);
        Permission::firstOrCreate(['name' => 'publish articles']);
        Permission::firstOrCreate(['name' => 'unpublish articles']);

        // create roles and assign existing permissions
        $role = Role::firstOrCreate(['name' => 'writer']);
        $role->givePermissionTo('edit articles');
        $role->givePermissionTo('delete articles');

        $role = Role::firstOrCreate(['name' => 'admin']);
        $role->givePermissionTo(['publish articles', 'unpublish articles']);
    }
}
```

Extending
---------

[](#extending)

If you need to EXTEND the existing `Role` or `Permission` models note that:

- Your `Role` model needs to extend the `Anggarasaja\Permission\Models\Role` model
- Your `Permission` model needs to extend the `Anggarasaja\Permission\Models\Permission` model

If you need to extend or replace the existing `Role` or `Permission` models you just need to keep the following things in mind:

- Your `Role` model needs to implement the `Anggarasaja\Permission\Contracts\Role` contract
- Your `Permission` model needs to implement the `Anggarasaja\Permission\Contracts\Permission` contract

In BOTH cases, whether extending or replacing, you will need to specify your new models in the configuration. To do this you must update the `models.role` and `models.permission` values in the configuration file after publishing the configuration with this command:

```
php artisan vendor:publish --provider="Anggarasaja\Permission\PermissionServiceProvider" --tag="config"
```

Cache
-----

[](#cache)

Role and Permission data are cached to speed up performance.

When you use the supplied methods for manipulating roles and permissions, the cache is automatically reset for you:

```
$user->assignRole('writer');
$user->removeRole('writer');
$user->syncRoles(params);
$role->givePermissionTo('edit articles');
$role->revokePermissionTo('edit articles');
$role->syncPermissions(params);
$permission->assignRole('writer');
$permission->removeRole('writer');
$permission->syncRoles(params);
```

HOWEVER, if you manipulate permission/role data directly in the database instead of calling the supplied methods, then you will not see the changes reflected in the application unless you manually reset the cache.

### Manual cache reset

[](#manual-cache-reset)

To manually reset the cache for this package, run:

```
php artisan cache:forget anggarasaja.permission.cache
```

### Cache Identifier

[](#cache-identifier)

> Note: If you are leveraging a caching service such as `redis` or `memcached` and there are other sites running on your server, you could run into cache clashes. It is prudent to set your own cache `prefix` in `/config/cache.php` for each application uniquely. This will prevent other applications from accidentally using/changing your cached data.

Need a UI?
----------

[](#need-a-ui)

As we are based on [laravel-permission](https://github.com/spatie/laravel-permission). The package doesn't come with any screens out of the box, you should build that yourself. To get started check out [this extensive tutorial](https://scotch.io/tutorials/user-authorization-in-laravel-54-with-spatie-laravel-permission) by [Caleb Oki](http://www.caleboki.com/).

Change log
----------

[](#change-log)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Testing
-------

[](#testing)

```
composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [Mostafa Anggarasaja](https://github.com/anggarasaja)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

29

—

LowBetter than 63% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 90.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~8 days

Total

31

Last Release

2872d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b466cff4ab52e605c025f36fd597db743dded136e99e8df7b78233fe5f1ff9c5?d=identicon)[anggarasaja](/maintainers/anggarasaja)

---

Top Contributors

[![mostafamaklad](https://avatars.githubusercontent.com/u/1166483?v=4)](https://github.com/mostafamaklad "mostafamaklad (283 commits)")[![makladuxbert](https://avatars.githubusercontent.com/u/61378154?v=4)](https://github.com/makladuxbert "makladuxbert (15 commits)")[![anggarasaja](https://avatars.githubusercontent.com/u/5020213?v=4)](https://github.com/anggarasaja "anggarasaja (11 commits)")[![efueger](https://avatars.githubusercontent.com/u/2053833?v=4)](https://github.com/efueger "efueger (2 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (1 commits)")

---

Tags

spatielaravelsecurityaclpermissionmongodbjenssegersMakladmostafamakladmostafa

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/anggarasaja-laravel-permission-mongodb/health.svg)

```
[![Health](https://phpackages.com/badges/anggarasaja-laravel-permission-mongodb/health.svg)](https://phpackages.com/packages/anggarasaja-laravel-permission-mongodb)
```

###  Alternatives

[mostafamaklad/laravel-permission-mongodb

Permission handling for Laravel 5.2 and up using mongodb

116218.2k2](/packages/mostafamaklad-laravel-permission-mongodb)[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.8k86.3M864](/packages/spatie-laravel-permission)[konekt/acl

Concord Module for Permission handling (Laravel 10 - 12)

1070.1k1](/packages/konekt-acl)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
