Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rehmatworks/3b87c9cc14814604d3a082abb8e8712a to your computer and use it in GitHub Desktop.
Save rehmatworks/3b87c9cc14814604d3a082abb8e8712a to your computer and use it in GitHub Desktop.
An example usage of Spatie role and permissions for Laravel
<?php
use App\User;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
$editorRole = Role::create(['name' => 'Editor']);
$userRole = Role::create(['name' => 'User']);
$adminRole = Role::create(['name' => 'Admin']);
// Permissions
$editorPermissions = ['manage-settings', 'manage-users'];
$userPermissions = ['manage-articles', 'manage-comments'];
$adminPermissions = array_merge($editorPermissions, $userPermissions);
// Assign Permissions
foreach($editorPermissions as $perm)
{
$create = Permission::create(['name' => $perm]);
$editorRole->givePermissionTo($create);
}
foreach($userPermissions as $perm)
{
$create = Permission::create(['name' => $perm]);
$userRole->givePermissionTo($create);
}
foreach($adminPermissions as $perm)
{
$create = Permission::create(['name' => $perm]);
$adminRole->givePermissionTo($create);
}
// Create Users
$editor = User::create([
'name' => 'Editor Demo',
'email' => 'editor@example.com',
'password' => bcrypt('password123')
]);
$editor->assignRole($editorRole);
$user = User::create([
'name' => 'User Demo',
'email' => 'user@example.com',
'password' => bcrypt('password123')
]);
$user->assignRole($userRole);
$admin = User::create([
'name' => 'admin Demo',
'email' => 'admin@example.com',
'password' => bcrypt('password123')
]);
$admin->assignRole($adminRole);
// Check for permissions
$user->can('manage-articles'); // True
$user->can('manage-settings'); // False
$admin->can('manage-settings'); // True
$admin->can('manage-articles'); // True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment