Skip to content
Kodeine edited this page Jun 12, 2015 · 6 revisions

Working With Permissions

Create Permissions

Lets create your first permission.

$permission = new Permission();
$permUser = $permission->create([ 
    'name'        => 'user',
    'slug'        => [          // pass an array of permissions.
        'create'     => true,
        'view'       => true,
        'update'     => true,
        'delete'     => true,
        'view.phone' => true
    ],
    'description' => 'manage user permissions'
]);

$permission = new Permission();
$permPost = $permission->create([ 
    'name'        => 'post',
    'slug'        => [          // pass an array of permissions.
        'create'     => true,
        'view'       => true,
        'update'     => true,
        'delete'     => true,
    ],
    'description' => 'manage post permissions'
]);

Assign Permission(s) to Role

Lets assign created permissions to a Role.

Note: You can pass an object, an array, role->id or just name.

$roleAdmin = Role::first(); // administrator
// permission as an object
$roleAdmin->assignPermission($permUser);
// as an id
$roleAdmin->assignPermission($permUser->id);
// or by name
$roleAdmin->assignPermission('user');
// or by collection
$roleAdmin->assignPermission(Permission::all());

Or multiple permissions at once:

// multiple permissions in an array
$roleAdmin->assignPermission(array($permUser, $permPost->id));
// or mutiple role slugs separated by comma or pipe.
$roleAdmin->assignPermission('user, post');

Note: The system will throw an exception if permission does not exists.

Revoke Permission(s) from Role

Similarly, you may revoke permissions from a role

Note: You can pass an object, an array, permission->id or just a name.

$roleAdmin = Role::first(); // administrator
// permission as an object
$roleAdmin->revokePermission($permUser);
// as an id
$roleAdmin->revokePermission($permUser->id);
// or by name
$roleAdmin->revokePermission('user');
// or by collection
$roleAdmin->revokePermission(Permission::all());

Or multiple permissions at once:

// multiple permissions in an array
$roleAdmin->assignPermission(array($permUser, $permPost->id));
// or mutiple role slugs separated by comma or pipe.
$roleAdmin->assignPermission('user, post');

Note: The system will throw an exception if role does not exists.

Sync Role Permissions

You can pass an array of role objects,ids or slugs to sync them to a user.

$roleAdmin->syncPermissions([1,2,3]);
$roleAdmin->syncPermissions('user, post');
$roleAdmin->syncPermissions((array($permUser, $permPost));
// or by collection
$roleAdmin->syncPermissions(Permission::all());

Note: The system will throw an exception if role does not exists.

Revoke All Permissions From A Role

You can revoke all roles assigned to a user.

$roleAdmin->revokeAllPermissions();

Get Role Permissions

Get permissions assigned to a role.

$roleAdmin->getPermissions();