PHPackages                             szykra/laravel-guard - 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. szykra/laravel-guard

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

szykra/laravel-guard
====================

Simple and easy to use roles and permissions system (ACL) for Laravel 5.

0.1.2(10y ago)151345MITPHP

Since Apr 4Pushed 9y ago3 watchersCompare

[ Source](https://github.com/skrajewski/laravel-guard)[ Packagist](https://packagist.org/packages/szykra/laravel-guard)[ RSS](/packages/szykra-laravel-guard/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (3)Versions (5)Used By (0)

Laravel Guard
=============

[](#laravel-guard)

[![version](https://camo.githubusercontent.com/6401b2d239193721deab58e4f9806707c7c32c9b89f26c6c4e93680f687fbf87/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f737a796b72612f6c61726176656c2d67756172642e737667)](https://camo.githubusercontent.com/6401b2d239193721deab58e4f9806707c7c32c9b89f26c6c4e93680f687fbf87/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f737a796b72612f6c61726176656c2d67756172642e737667)[![codeclimate](https://camo.githubusercontent.com/c42806f052f5a2f4c0f32b81ee3ab0d63879e441fc49e6c3920b3fd0f10a2670/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636c696d6174652f6769746875622f736b72616a6577736b692f6c61726176656c2d67756172642e737667)](https://camo.githubusercontent.com/c42806f052f5a2f4c0f32b81ee3ab0d63879e441fc49e6c3920b3fd0f10a2670/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636c696d6174652f6769746875622f736b72616a6577736b692f6c61726176656c2d67756172642e737667)[![license](https://camo.githubusercontent.com/aa26e057cba83966b782221056736c23c91364d5f0a940cc78b306f968d65c01/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f737a796b72612f6c61726176656c2d67756172642e737667)](https://camo.githubusercontent.com/aa26e057cba83966b782221056736c23c91364d5f0a940cc78b306f968d65c01/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f737a796b72612f6c61726176656c2d67756172642e737667)

Simple and easy to use roles and permissions system *(ACL)* for Laravel 5.

**Laravel Guard** is package to easy controlling access to parts of your system. It provides simple tool to protect your routes and user methods to checking permissions.

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

[](#installation)

### Install via composer

[](#install-via-composer)

Add dependency to your `composer.json` file and run `composer update`.

```
"szykra/laravel-guard": "~0.1.0"
```

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

[](#configuration)

### Make new migration to store roles and permissions

[](#make-new-migration-to-store-roles-and-permissions)

Currently Guard stores all information about roles and permissions in database.

```
Schema::create('roles', function(Blueprint $table)
{
    $table->increments('id');
    $table->string("tag", 20);
    $table->string("name", 100);
});

Schema::create('permissions', function(Blueprint $table)
{
    $table->increments('id');
    $table->string("tag", 50);
    $table->string("name", 50);
    $table->string("description");
});

Schema::create('permission_role', function(Blueprint $table)
{
    $table->increments('id');
    $table->unsignedInteger('role_id');
    $table->unsignedInteger('permission_id');

    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
    $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
});
```

Of course you should add new field to your *users* table to link user with *role*.

```
Schema::update('users', function(Blueprint $table)
{
    $table->unsignedInteger('role_id');

    $table->foreign('role_id')->references('id')->on('roles');
});
```

### Configure your **User** model

[](#configure-your-user-model)

Guard provides new *contract* - **Permissible**. It requires two methods:

- is($role)
- can($action)

Don't worry! Guard has trait which implements these methods. The only thing you have to do is use it and add new relationship to `roles`.

**User model**

```
use Szykra\Guard\Contracts\Permissible;
use Szykra\Guard\Traits\Permissions;

class User extends Model implements Permissible, AuthenticatableContract, CanResetPasswordContract {

	use Permissions, Authenticatable, CanResetPassword;

    public function role()
    {
        return $this->belongsTo('Szykra\Guard\Models\Role');
    }

}
```

Guard provides two new models to your application - **Role** and **Permission**. Don't worry about them - they are needed to retrieve information from database.

### Add service provider to your config

[](#add-service-provider-to-your-config)

Open your `config/app.php` file and add this line to `$providers` array

```
'Szykra\Guard\GuardServiceProvider'
```

Now **Permissible** interface is binding to currently logged user. You can inject it everywhere you need by *IoC Container* but remember - if you are not logged in then application throws *binding exception*. Always use this interface with `auth` middleware!

### Register new middleware

[](#register-new-middleware)

Open your `app/Http/Kernel.php` and add this line to `$middleware` array

```
'Szykra\Guard\Middleware\ProtectRoutes',
```

If you don't want to protect all routes you can register this middleware as `$routeMiddleware` and use it only in specific routes.

```
'guard' => 'Szykra\Guard\Middleware\ProtectRoutes'

```

Roles and permissions
---------------------

[](#roles-and-permissions)

Guard provides management for *Roles* and *Permissions* but what exactly does that mean?

In complex system we have a lot types of users, e.g. Administrators, Managers, Users or Moderators. This types are called **roles**. Users can perform a lot of actions at the system but specific types of users should have specified rights called **permissions**. When a user has a role, also has permissions that depend on his role. We can check these permissions to prevent or allow specific actions.

### Permission naming convention

[](#permission-naming-convention)

Guard does not defined how you should name your permissions. Try to keep it **simple**, **short**, **consistent** and **easy to remember**. I really like use a simple notation ***RESOURCE.ACTION***, e.g. `USERS.READ`, `USERS.UPDATE`. Feel free to use own naming convention, e.g. `read users`, `update user`. The choice is yours!

### Creating Roles and Permissions

[](#creating-roles-and-permissions)

You have a lot of possibilities to create *Roles* or *Permissions*. You can manually insert data to database, create special *Seeder* to prepare data or use artisan **Guard commands** to create *Role* and *Permission* entries on demand.

#### Create using Artisan CLI

[](#create-using-artisan-cli)

Guard provides new *artisan* commands:

- `guard:grant role permission`
- `guard:make:role tag [name]`
- `guard:make:permission tag [name]`

To create new role run below command:

```
php artisan guard:make:role ADMIN Administrator
```

Create new permission

```
php artisan guard:make:permission USERS.READ
```

To create permission and instantly link it with role use *--role* option

```
php artisan guard:make:permission USERS.CREATE -r ADMIN
```

To link existing role with permission use `guard:grant` command

```
php artisan guard:grant ADMIN USERS.READ
```

#### Create using *Seeder*

[](#create-using-seeder)

If you have a lot of roles and permissions then seeder is a good choice, e.g.

```
use Szykra\Guard\Models\Permission;
use Szykra\Guard\Models\Role;
use Illuminate\Database\Seeder;

class GuardTableSeeder extends Seeder
{
    public function run()
    {
        $roles = [
            'ADMIN'  => 'Administrator',
            'EDITOR' => 'Content Editor'
        ];

        $permissions = [
            ['tag' => 'POSTS.CREATE', 'name' => 'Create posts', 'description' => 'Ability to create new post'],
            ['tag' => 'POSTS.READ', 'name' => 'Read posts', 'description' => 'Ability to read posts data'],
            ['tag' => 'POSTS.UPDATE', 'name' => 'Update posts', 'description' => 'Ability to update posts data'],
            ['tag' => 'POSTS.DELETE', 'name' => 'Delete posts', 'description' => 'Ability to delete posts']
        ];

        $permModels = [];

        foreach ($permissions as $perm) {
            $permModels[$perm['tag']] = Permission::create($perm);
        }

        $rolesToPerm = [
            'ADMIN'  => ['POSTS.CREATE', 'POSTS.READ', 'POSTS.UPDATE', 'POSTS.DELETE'],
            'EDITOR' => ['POSTS.CREATE', 'POSTS.READ', 'POSTS.UPDATE']
        ];

        foreach ($rolesToPerm as $tag => $permissions) {
            $name = $roles[$tag];
            $role = Role::create(compact('tag', 'name'));

            foreach ($permissions as $perm) {
                $role->permissions()->save($permModels[$perm]);
            }
        }
    }
}
```

Usage
-----

[](#usage)

### Route protection

[](#route-protection)

To protect your route define key `needs` in route array

```
/* String */
$router->get('/users', [
	'as' => 'users.index',
	'uses' => 'UsersController@index',
	'needs' => 'USERS.READ'
]);

/* As array */
$router->get('/users/{id}', [
	'as' => 'users.show',
	'uses' => 'UsersController@show',
	'needs' => ['USERS.READ']
]);
```

You can require more permissions for single route:

```
/* String - separate by pipe */
$router->post('/users', [
	'as' => 'users.store',
	'uses' => 'UsersController@store',
	'needs' => 'USERS.READ|USERS.CREATE'
]);

/* As array */
$router->put('/users', [
	'as' => 'users.update',
	'uses' => 'UsersController@update',
	'needs' => ['USERS.READ', 'USERS.CREATE']
]);
```

If you are define Guard as `$routeMiddleware` you must add `middleware` action:

```
$router->put('/users', [
	'as' => 'users.update',
	'uses' => 'UsersController@update',
	'needs' => ['USERS.READ', 'USERS.CREATE'],
	'middleware' => 'guard'
]);
```

Of course you can group your routes with required permissions:

```
$router->group(['needs' => ['USERS.READ']], function() use ($router)
{
    // Needs USERS.READ permission
    $router->get('/users/{id}', [
        'as' => 'users.show',
        'uses' => 'UsersController@show',
    ]);

    // Needs USERS.READ and USERS.UPDATE permissions
    $router->put('/users/{id}', [
        'as' => 'users.update',
        'uses' => 'UsersController@update',
        'needs' => ['USERS.UPDATE']
    ]);
});
```

Checking permissions
--------------------

[](#checking-permissions)

You have two new methods in user model to checking permissions.

- `$user->can($action)`
- `$user->is($role)`

To get user instance use Laravel `Auth` facade or inject instance of **Permissible** into your class.

### Inject to constuctor

[](#inject-to-constuctor)

```
use Szykra\Guard\Contracts\Permissible;

class UsersController extends Controller {

    public function __construct(Permissible $user)
    {
        $this->user = $user;
    }

    public function update(Request $request, $id)
    {
        if( ! $this->user->can('USERS.UPDATE')) {
            // redirect, exception, flash message, etc.
        }

        // do something with user
    }

}
```

### Inject to action

[](#inject-to-action)

```
use Szykra\Guard\Contracts\Permissible;

class UsersController extends Controller {

    public function destroy(Permissible $user, $id)
    {
        if( ! $user->can('USERS.DELETE')) {
            // redirect, exception, flash message, etc.
        }

        // destroy user
    }

}
```

### Retrieve user by *Auth* facade

[](#retrieve-user-by-auth-facade)

You can check permissions wherever you have instance of current authenticated user, e.g. by `Auth::user()`. It's very useful in views, when you have to render a part of view only for users with specific permissions.

```

    Show

    @if(Auth::user()->can('USERS.EDIT'))
        | Edit
    @endif

```

### Checking permissions in *Form Request*

[](#checking-permissions-in-form-request)

Laravel 5 Form Requests are very nice places to checking permissions. See below example.

```
use Szykra\Guard\Contracts\Permissible;

class CreateUserRequest extends Request {

	public function authorize(Permissible $user)
	{
		return $user->can("USERS.CREATE");
	}

	public function rules()
	{
        return [
            // your validation rules
        ];
	}

}
```

Reaction when user has not enough permissions
---------------------------------------------

[](#reaction-when-user-has-not-enough-permissions)

If user has not enough permissions then Guard thrown `InsufficientPermissionException`. You can catch it and return view, redirect or something else.

To catch this exception globally use your *ExceptionHandler*, e.g. `app/Exception/Handler.php`, method `render()`

```
public function render($request, Exception $e)
{
    if($e instanceof InsufficientPermissionException) {
        Flash::warning("Insufficient permissions", "You don't have enough permission to access to this section.");

        return redirect()->route('home');
    }

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

License
-------

[](#license)

The MIT License. Copyright © 2015 Szymon Krajewski.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88.2% 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 ~56 days

Total

3

Last Release

3950d ago

### Community

Maintainers

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

---

Top Contributors

[![skrajewski](https://avatars.githubusercontent.com/u/4791560?v=4)](https://github.com/skrajewski "skrajewski (15 commits)")[![dvdmarchetti](https://avatars.githubusercontent.com/u/1494034?v=4)](https://github.com/dvdmarchetti "dvdmarchetti (1 commits)")[![sebastiaanfranken](https://avatars.githubusercontent.com/u/608882?v=4)](https://github.com/sebastiaanfranken "sebastiaanfranken (1 commits)")

---

Tags

laravelaclrolespermissionsroute

### Embed Badge

![Health badge](/badges/szykra-laravel-guard/health.svg)

```
[![Health](https://phpackages.com/badges/szykra-laravel-guard/health.svg)](https://phpackages.com/packages/szykra-laravel-guard)
```

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k89.8M1.0k](/packages/spatie-laravel-permission)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[hasinhayder/tyro

Tyro - The ultimate Authentication, Authorization, and Role &amp; Privilege Management solution for Laravel 12 &amp; 13

6712.1k2](/packages/hasinhayder-tyro)[beatswitch/lock-laravel

A Laravel Driver for Lock.

15529.1k1](/packages/beatswitch-lock-laravel)[wnikk/laravel-access-rules

Simple system of ACR (access control rules) for Laravel, with roles, groups, unlimited inheritance and possibility of multiplayer use.

103.6k1](/packages/wnikk-laravel-access-rules)[erag/laravel-role-permission

A simple and easy-to-install role and permission management package for Laravel, supporting versions 10.x and 11.x

404.2k](/packages/erag-laravel-role-permission)

PHPackages © 2026

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