PHPackages                             vi-kon/laravel-auth - 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. vi-kon/laravel-auth

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

vi-kon/laravel-auth
===================

Role-permission based authenticator for Laravel 5.2

v3.1.0(10y ago)33852MITPHPPHP &gt;=5.5.9

Since May 23Pushed 10y ago1 watchersCompare

[ Source](https://github.com/vi-kon/laravel-auth)[ Packagist](https://packagist.org/packages/vi-kon/laravel-auth)[ Docs](https://github.com/vi-kon/laravel-auth)[ RSS](/packages/vi-kon-laravel-auth/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (7)Versions (24)Used By (0)

Laravel 5.2 role-permission based authentication
================================================

[](#laravel-52-role-permission-based-authentication)

This is **Laravel 5** package for role-permission based authenticating.

Table of content
----------------

[](#table-of-content)

- [Features](#features)
- [Todo](#todo)
- [Installation](#installation)
- [Models](#models)
- [Helper classes](#helper-classes)
- [Middleware](#middleware)
- [Packages](#packages)

---

[Back to top](#laravel-5-role-based-authentication)

Features
--------

[](#features)

- Permission based access
- Grouping permissions (Roles)
- Restrict routes access by individual permission(s) or role(s)
- Allow to use same username, separated to individual namespaces (each namespace require individual login screen or option to specify namespace at login)

---

[Back to top](#laravel-5-role-based-authentication)

Todo
----

[](#todo)

- Fix incoming bugs
- Finish documentation
- Write tests
- Cache metadata

---

[Back to top](#laravel-5-role-based-authentication)

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

[](#installation)

#### Composer

[](#composer)

There are multiple way to install package via composer

- To your `composer.json` file add following lines:

    ```
    // to your "require" object
    "vi-kon/laravel-auth": "^3.0"
    ```
- Or run following command in project root:

    ```
    composer require vi-kon/laravel-auth
    ```

    This command will add above line in your composer.json file and download required package files.

#### Setup

[](#setup)

In your Laravel 5.1 project add following lines to `config/app.php`:

```
// to providers array
\ViKon\Auth\AuthServiceProvider::class,
```

---

[Back to top](#laravel-5-role-based-authentication)

### Aliases

[](#aliases)

Optionally you can add aliases back to `app.php`:

```
// to aliases array
'RouterAuth' => \ViKon\Auth\Facades\RouterAuth::class,
```

---

[Back to top](#laravel-5-role-based-authentication)

### Middleware

[](#middleware)

No need to assign short-hand key to `App\Http\Kernel`'s `routeMiddleware` property, because `AuthServiceProvider` do it automatically. These middlewares are:

- [HasAccessMiddleware](#has-access-middleware)
- [LoginRedirectorMiddleware](#login-redirector-middleware)
- [PermissionMiddleware](#permission-middleware)

#### Has Access middleware

[](#has-access-middleware)

Has access middleware can attach to groups or routes. This middleware check if route has assigned permission and if current user has permission to access that route.

##### Usage

[](#usage)

Part of `routes.php`:

```
// Single route
Route::get('/', [
    'middleware' => 'auth.has-access',
    'permission' => 'access.some.controller',
    'uses'       => 'SomeController@index',

]);
// Multiple routes in group
Route::group(['middleware' => 'auth.has-access'], function () {
    // ...
    Route::get('/', [
        'permission' => 'access.some.controller',
        'uses'       => 'SomeController@index',
    ]);
    // ...
});
```

#### Login redirector middleware

[](#login-redirector-middleware)

This middleware allow to redirect user (if not authenticated) to custom login page. It is useful if users are separated to individual namespaces and some routes belongs to first namespace and some routes belongs to second namespace.

#### Permission middleware

[](#permission-middleware)

Permission middleware get permission from their argument and restrict user if has no permission to access the route.

---

[Back to top](#laravel-5-role-based-authentication)

Models
------

[](#models)

All models have configurable database names. These database names are hold under `table.*` config value. In this short introduction default table names are used. The package holds following models:

- [User](#user-model)
- [Role](#role-model)
- [Permission](#permission-model)
- [Group](#group-model)
- [UserPasswordReminder](#userpasswordreminder-model)
- [Profile](#profile-model)

Models are using pivot tables for many to many relations: `rel__role__group`, `rel__user__role`, `rel__user__group`.

> **Note**: All table names, even pivot table names are configurable via config file.

> **Warning**: Not recommended to change table names if database is already migrated, because migrations down method will try to execute on wrong tables.

---

[Back to top](#laravel-5-role-based-authentication)

### User model

[](#user-model)

User representing model, implements `AuthenticatableContract` and `CanResetPasswordContract` interfaces and use `Authenticatable` and `CanResetPassword` traits.

**Namespace**: `ViKon\Auth\Model`

**Database table**: `users`

#### Read/Write Properties

[](#readwrite-properties)

TypeNameDescriptionDefaultDatabaseinteger`id`Unique user identifier-primary key, incrementsstring`username`Username-string`password`User password-length 255string`email`User e-mail address-length 255string`remember_token`Remember token for "Remember me"nullnullablestring`package`Package name"system"length 255string`home`User home route namenullnullableboolean`blocked`Check if user is blockedfalseboolean`static`Disallow deleting on GUIfalseboolean`hidden`Disallow showing on GUIfalseThe `username` and `package` columns has contracted unique index.

#### Read properties (relations)

[](#read-properties-relations)

TypeNameDescriptionDefaultDatabase\\ViKon\\Auth\\Model\\Role\[\]`roles`Roles collection-many to many relation with `user_roles` table\\ViKon\\Auth\\Model\\Permission\[\]`permissions`Permissions collection-many to many relation with `user_permissions` table\\ViKon\\Auth\\Model\\Reminder\[\]`reminders`Reminders collection-many to many relation with `user_password_reminders` table#### Methods (relations)

[](#methods-relations)

Relations for Laravel Query Builder.

TypeNameDescriptionDatabaseBelongsToMany`roles()`Users relation for query buildermany to many relation with `user_roles` tableBelongsToMany`permissions()`Permissions relation for query buildermany to many relation with `user_permissions` tableBelongsToMany`reminders()`Reminders relation for query buildermany to many relation with `user_password_reminders` tableHasOne`profile()`Return attached user profileone to one relation to `user_profile` table (this table can customized via custom Profile model)---

[Back to top](#laravel-5-role-based-authentication)

### Role model

[](#role-model)

Role is for managing user permissions as collection. So this is a helper to add multiple permissions to user. Each role can contain multiple permissions.

**Namespace**: `ViKon\Auth\Model`

**Database table**: `user_roles`

#### Read/Write Properties

[](#readwrite-properties-1)

TypeNameDescriptionDefaultDatabaseinteger`id`Unique role identifier-primary key, incrementsstring`token`Unique role name (token)nullunique, nullableboolean`static`Disallow deleting on GUIfalseboolean`hidden`Disallow showing on GUIfalse#### Read properties (relations)

[](#read-properties-relations-1)

TypeNameDescriptionDefaultDatabase\\ViKon\\Auth\\Model\\User\[\]`users`Users collection-many to many relation with `users` table\\ViKon\\Auth\\Model\\Permission\[\]`permissions`Permissions collection-many to many relation with `user_permissions` table#### Methods (relations)

[](#methods-relations-1)

Relations for Laravel Query Builder.

TypeNameDescriptionDatabaseBelongsToMany`users()`Users relation for query buildermany to many relation with `users` tableBelongsToMany`permissions()`Roles relation for query buildermany to many relation with `user_permissions` table---

[Back to top](#laravel-5-role-based-authentication)

### Permission model

[](#permission-model)

Permissions is for granting some kind of access to users, like access routes or certain actions. Each action should have individual permissions.

For example in REST controller should have `{action name}.index`, `{action name}.show` `{action name}.create`, `{action name}.edit` and `{action name}.destroy` permissions for individual actions.

**Namespace**: `ViKon\Auth\Model`

**Database table**: `user_permissions`

#### Read/Write Properties

[](#readwrite-properties-2)

TypeNameDescriptionDefaultDatabaseinteger`id`Unique permissions identifier-primary key, incrementsstring`token`Unique permissions token-unique#### Read properties (relations)

[](#read-properties-relations-2)

TypeNameDescriptionDefaultDatabase\\ViKon\\Auth\\Model\\User\[\]`users`Users collection-many to many relation with `users` table\\ViKon\\Auth\\Model\\Role\[\]`roles`Roles collection-many to many relation with `user_roles` table#### Methods (relations)

[](#methods-relations-2)

Relations for Laravel Query Builder.

TypeNameDescriptionDatabaseBelongsToMany`users()`Users relation for query buildermany to many relation with `users` tableBelongsToMany`roles()`Roles relation for query buildermany to many relation with `user_roles` table---

[Back to top](#laravel-5-role-based-authentication)

### UserPasswordReminder model

[](#userpasswordreminder-model)

Stores password reminder tokens with store time.

**Namespace**: `ViKon\Auth\Model`

**Database table**: `user_password_reminders`

#### Read/Write Properties

[](#readwrite-properties-3)

TypeNameDescriptionDefaultDatabaseinteger`id`Unique reminder identifier-primary key, incrementsinteger`user_id`User id-indexstring`token`Password token-Carbon`created_at`Created at time-#### Read properties (relations)

[](#read-properties-relations-3)

TypeNameDescriptionDefaultDatabase\\ViKon\\Auth\\Model\\User`user`User model-many to one relation with `users` table#### Methods (relations)

[](#methods-relations-3)

Relations for Laravel Query Builder.

TypeNameDescriptionDatabaseBelongsTo`user()`User relation for query buildermany to many relation with `users` table---

[Back to top](#laravel-5-role-based-authentication)

### Profile model

[](#profile-model)

Profile model is not implemented in this package. This is only for support to add custom data to users via single one to one relation. In config with `profile`option can customize Profile model location.

Profile model has only one restriction. Need to have `user_id` column, which is point to User's model `id` column.

Short example for profile migration file:

```
class CreateProfileTable extends Migration
{
    public function up()
    {
        Schema::create('user_profile', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->increments('id');

            // Foreign connection to user table
            $table->unsignedInteger('user_id')
                  ->unique();
            $table->foreign('user_id')
                  ->references('id')
                  ->on('users')
                  ->onUpdate('cascade')
                  ->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::drop('user_profile');
    }
}
```

---

[Back to top](#laravel-5-role-based-authentication)

Helper classes
--------------

[](#helper-classes)

- [Guard class](#guard-class)
- [RouterAuth class](#routerauth-class)

### Guard class

[](#guard-class)

The `Guard` class extends Laravel's default `Guard` class to grant access for new features. These features allow to get permission for current user, check if user is blocked or not.

### Methods

[](#methods)

Some methods are not newly implemented, just overwritten.

- [attempt](#guardAttempt) - try to authenticate user with credentials (auto inject into credentials default role package if set)
- [hasPermission](#guardHasPermission) - check if authenticated user has a specific permission
- [hasPermissions](#guardHasPermissions) - check if authenticated user has multiple permissions at once
- [isBlocked](#guardIsBlocked) - check if authenticated user is blocked or not
- [user](#guardUser) - get authenticated user

TODO method descriptions

---

[Back to top](#laravel-5-role-based-authentication)

### RouterAuth class

[](#routerauth-class)

The `RouterAuth` class allow to get authentication information from route.

### Methods

[](#methods-1)

- [hasAccess](#routerAuthHasAccess) - get roles for a named route
- [isPublic](#routerAuthIsPublic) - check if current user has access to named route
- [getPermissions](#routerAuthGetPermissions) - check if route is public (route has no permissions)

TODO method descriptions

---

[Back to top](#laravel-5-role-based-authentication)

Middleware
----------

[](#middleware-1)

Middleware classes allow to filter individual routes by their attached permissions.

- [HasAccessMiddleware](#hasaccess-middleware) - check if authenticated user have single or multiple permissions to current route
- [HasAccessMiddleware](#hasaccess-middleware) - check if authenticated user have single permission to current route

> **Note:** Syntax is only difference between these middlewares.

---

[Back to top](#laravel-5-role-based-authentication)

### PermissionMiddleware middleware

[](#permissionmiddleware-middleware)

> **Note:** The router cannot get parameter from this middleware.

### HasAccessMiddleware middleware

[](#hasaccessmiddleware-middleware)

Check if authenticated user have all permissions to current route. To add permission(s) to route only need add `permissions` key to route options with right permissions.

```
Router::get('/', [
    'permissions' => 'permission.name',
]);
```

Or if multiple permissions are passed (Authenticated user have to has all permissions to access route):

```
Router::get('/', [
    'permissions' => [
        'permission.first.name',
        'permission.second.name',
    ],
]);
```

> **Note**: If current route's `permissions` key is empty or not exists, then route is mark as public and no route restriction will made.

#### Configuration

[](#configuration)

With `php artisan vendor:publish --provider="ViKon\Auth\AuthServiceProvider" --tag="config"`command you can publish all config files to `vi-kon/auth.php`.

In this file there are multiple options. The following options are available:

- **login.route** - login screen route name
- **error-403.route** - route name if user is already authenticated but has no access to route

If user is not authenticated and route is not public, then middlewares redirect user to named route, where named route name is stored in `login.route`config value.

If user is authenticated and hasn't got enough permissions to access route, then middlewares redirect to named route stored in `error-403.route` config value.

Otherwise middlewares allow access to route.

> **Note:** The `login.route` and `error-403.route` stores the route name.

On 403 error the following parameters are flashed to session during redirect:

- **route-request-uri** - with full URL
- **route-roles** - array with list of roles needed by route

#### Usage

[](#usage-1)

```
// check if user have "admin" role
$options = [
    'middleware'  => 'auth.role',
    'permissions' => 'admin',
];
Route::get('URL', $options);

// check if user have "admin" and "superadmin" roles
$options = [
    'middleware'  => 'auth.role',
    'permissions' => ['admin', 'superadmin'],
];
Route::get('URL', $options);
```

---

[Back to top](#laravel-5-role-based-authentication)

Namespaces
----------

[](#namespaces)

Namespaces are useful for grouping users into individual login groups. In each namespace usernames are unique, however in other namespace using the same username is permitted.

The default package is `system`. All users are stored in this package.

### Authentication

[](#authentication)

For authenticating user in default namespace is simple, just call `attempt` method as usual:

```
if (Auth::attempt(['email' => $email, 'password' => $password]))
{
    return redirect()->intended('dashboard');
}
```

For authenticating in custom namespace, need to provide namespace name:

```
if (Auth::attempt(['email' => $email, 'password' => $password, 'namespace' => $namespace]))
{
    return redirect()->intended('dashboard');
}
```

---

[Back to top](#laravel-5-role-based-authentication)

License
-------

[](#license)

This package is licensed under the MIT License

---

[Back to top](#laravel-5-role-based-authentication)

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~33 days

Recently: every ~42 days

Total

22

Last Release

3719d ago

Major Versions

v1.0.5 → 4.1.x-dev2014-06-15

v1.1.3 → 4.2.x-dev2014-11-07

v1.1.4 → v2.0.02015-03-10

v2.0.1 → v3.0.0-RC12015-11-12

PHP version history (3 changes)v1.0.0PHP &gt;=5.3.0

v1.1.0PHP &gt;=5.4.0

v3.0.0-RC1PHP &gt;=5.5.9

### Community

Maintainers

![](https://www.gravatar.com/avatar/97ac6badd847093e56369390bf36ddbb8740e10a8a495b339c2adb78e7345663?d=identicon)[vincekovacs](/maintainers/vincekovacs)

---

Top Contributors

[![vincekovacs](https://avatars.githubusercontent.com/u/1031595?v=4)](https://github.com/vincekovacs "vincekovacs (187 commits)")

---

Tags

laravelAuthenticationpermissionrouterole

### Embed Badge

![Health badge](/badges/vi-kon-laravel-auth/health.svg)

```
[![Health](https://phpackages.com/badges/vi-kon-laravel-auth/health.svg)](https://phpackages.com/packages/vi-kon-laravel-auth)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[api-platform/laravel

API Platform support for Laravel

58171.4k14](/packages/api-platform-laravel)[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k102.4M1.4k](/packages/spatie-laravel-permission)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M131](/packages/roots-acorn)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k15.1M132](/packages/laravel-pulse)[mike-bronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k90.5k1](/packages/mike-bronner-laravel-model-caching)

PHPackages © 2026

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