despark / laravel-permission-roles
Permission roles package for laravel framework
v2.0.0
2015-10-16 14:33 UTC
Requires
- php: >=5.4.0
- illuminate/auth: 5.1.*
- illuminate/database: 5.1.*
- illuminate/routing: 5.1.*
- illuminate/support: 5.1.*
This package is not auto-updated.
Last update: 2024-11-13 10:39:53 UTC
README
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); }
- 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'
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'); } );