PHP code example of bhhaskin / laravel-roles-permissions

1. Go to this page and download the library: Download bhhaskin/laravel-roles-permissions library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bhhaskin / laravel-roles-permissions example snippets


use Bhhaskin\RolesPermissions\Models\Permission;
use Bhhaskin\RolesPermissions\Models\Role;
use Bhhaskin\RolesPermissions\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;
}

$admin = Role::create(['name' => 'Administrator', 'slug' => 'admin']);
$editor = Role::create(['name' => 'Editor', 'slug' => 'editor']);
$publishPosts = Permission::create(['name' => 'Publish posts', 'slug' => 'publish-posts']);

$user->assignRole($admin);
$user->givePermission($publishPosts);

$user->hasRole('admin'); // true
$user->hasPermission('publish-posts'); // true
$admin->uuid; // UUIDs are generated automatically for frontend consumers

config(['roles-permissions.object_permissions.enabled' => true]);

$editor = Role::create(['name' => 'Project Editor', 'slug' => 'project-editor']);
$approve = Permission::create(['name' => 'Approve Post', 'slug' => 'approve-post']);

$editor->permissions()->attach($approve);

$user->assignRole($editor, $post); // scoped to this $post instance
$user->givePermission($approve, $post); // direct permission for this post

$user->hasRole('project-editor', $post); // true
$user->hasPermission('approve-post', $post); // true
$user->hasPermission('approve-post'); // false, only scoped to the post

'role_scopes' => [
    'team' => App\\Models\\Team::class,
    'organization' => App\\Models\\Organization::class,
],

Role::forScope('team')->get(); // only team roles
Permission::forScope('organization')->get(); // permissions scoped to organizations

$permission = Permission::factory()
    ->forScope('organization')
    ->create([
        'name' => 'View Organization Metrics',
        'slug' => 'view-org-metrics',
    ]);

Role::factory()
    ->forScope('organization')
    ->create(['name' => 'Organization Analyst', 'slug' => 'org-analyst'])
    ->permissions()
    ->attach($permission);

$orgPermissionSlugs = Permission::forScope('organization')->pluck('slug');
bash
php artisan migrate
bash
php artisan vendor:publish --provider="Bhhaskin\RolesPermissions\RolesPermissionsServiceProvider" --tag="laravel-roles-permissions-factories"
php artisan vendor:publish --provider="Bhhaskin\RolesPermissions\RolesPermissionsServiceProvider" --tag="laravel-roles-permissions-seeders"