-
Notifications
You must be signed in to change notification settings - Fork 216
Create Roles
徐文志程序猿 edited this page Aug 12, 2016
·
6 revisions
Lets create your first roles.
$roleAdmin = new Role();
$roleAdmin->name = 'Administrator';
$roleAdmin->slug = 'administrator';
$roleAdmin->description = 'manage administration privileges';
$roleAdmin->save();
//or create array method
$role = new Role();
$roleAdmin = $role->create([
'name' => 'Administrator',
'slug' => 'administrator',
'description' => 'manage administration privileges'
]);
$role = new Role();
$roleModerator = $role->create([
'name' => 'Moderator',
'slug' => 'moderator',
'description' => 'manage moderator privileges'
]);
Lets assign created roles to a User.
Note: You can pass an object, an array, role->id or just a slug.
Before, You should do first, use the HasRole trait in Your User Model.
//...ignore
use Kodeine\Acl\Traits\HasRole;
class User extends Model
{
use HasRole;
//...ignore
$user = User::find(1);
// by object
$user->assignRole($roleAdmin);
// or by id
$user->assignRole($roleAdmin->id);
// or by just a slug
$user->assignRole('administrator');
Or multiple roles
at once:
// multiple roles in an array
$user->assignRole(array($roleAdmin, $roleModerator));
// or mutiple role slugs separated by comma or pipe.
$user->assignRole('administrator, moderator');
Note: The system will throw an exception if role does not exists.
Similarly, you may revoke roles from user
Note: You can pass an object, an array, role->id or just a slug.
$user = User::find(1);
// by object
$user->revokeRole($roleAdmin);
// or by id
$user->revokeRole($roleAdmin->id);
// or by just a slug
$user->revokeRole('administrator');
Or multiple roles
at once:
// multiple roles in an array
$user->revokeRole(array($roleAdmin, $roleModerator));
// or mutiple role slugs separated by comma or pipe.
$user->revokeRole('administrator, moderator');
Note: The system will throw an exception if role does not exists.
You can pass an array of role objects,ids or slugs to sync them to a user.
$user->syncRoles([1,2,3]);
$user->syncRoles('administrator, moderator');
$user->syncRoles((array($roleAdmin, $roleModerator));
Note: The system will throw an exception if role does not exists.
You can revoke all roles assigned to a user.
$user->revokeAllRoles();
Get roles assigned to a user.
$user = User::first();
$user->getRoles();