despark / laravel-permission-roles by tbanov

34
3
10
Package Data
Maintainer Username: tbanov
Maintainer Contact: tbanov@despark.com (Tihomir Banov)
Package Create Date: 2015-06-05
Package Last Update: 2016-12-22
Language: PHP
License: MIT
Last Refreshed: 2024-11-22 03:03:42
Package Statistics
Total Downloads: 34
Monthly Downloads: 1
Daily Downloads: 0
Total Stars: 3
Total Watchers: 10
Total Forks: 0
Total Open Issues: 1

Laravel Permission Roles

Installation

Open composer.json file of your project and add the following to the require array:


"despark/laravel-permission-roles" : "1.0.*"

Now run composer update to install the new requirement.

Once it's installed, you need to register the service provider in app/config/app.php in the providers array:


'providers' => array(
  ...
  'Despark\LaravelPermissionRoles\LaravelPermissionRolesServiceProvider',
);

Migrate required tables: php artisan migrate --package="despark/laravel-permission-roles" command will create: roles, role_user, permissions, permission_role - tables

How to use it

  • User Model Example

use Despark\LaravelPermissionRoles\PermissionTrait;

class User extends Eloquent
{
    use PermissionTrait;
}

  • Attach Role to User

$input = Input::all();
$user = new User();
$user = $user->create($input);
$user->attachRole(array_get($input, 'role'));

  • Update user Role

$user = User::findOrFail($id)
$user->changeRole(Input::get('role'));

  • Use Role Model

use Despark\LaravelPermissionRoles\Role;

class RoleController extends BaseController
{
	Role::findOrFail($id);
}

Roles table alt tag

  • Add permissions to Role

$input = Input::all();
$role = Role::findOrFail($id);
$role->update($input);
if ($role->permissions->count()) {
    $role->permissions()->detach($role->permissions->lists('id'));
    $role->permissions()->attach(array_get($input, 'permissions'));
}

  • Check if current user has permission

Auth::user()->canLoginToAdmin()  // permission slug 'login_to_admin'

Auth::user()->canAddUsers()  // permission slug 'edit_user'

Auth::user()->canEditUsers()  // permission slug 'edit_page'

Permissions table alt tag

Permission based routes

filters.php


Route::filter('admin.permission', function () {

    $route = explode('/', \Route::getCurrentRoute()->getPath());

    if (!Auth::user()->can('edit_'.str_replace('-', '_', array_get($route, 1)))) {
        throw new \Exception("Sorry, you don't have permission to access this page.");
    }
});

routes.php


Route::group(
    ['before' => 'admin.permission'], function () {
        Route::resource('user', 'UserController');
    }
);

Route::group(
    ['before' => 'admin.permission'], function () {
        Route::resource('page', 'PageController');

    }
);