Last active
July 20, 2018 11:01
-
-
Save rehmatworks/3b87c9cc14814604d3a082abb8e8712a to your computer and use it in GitHub Desktop.
An example usage of Spatie role and permissions for Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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