PHP code example of isakzhanov-r / laravel-permissions

1. Go to this page and download the library: Download isakzhanov-r/laravel-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/ */

    

isakzhanov-r / laravel-permissions example snippets


IsakzhanovR\Permissions\ServiceProvider::class;

namespace App\Models;

use IsakzhanovR\Permissions\Models\Role as LaravelRole;

final class Role extends LaravelRole
{
        protected $fillable = [
            'title',
            'slug',
            'description',
        ];
}

return [
//...
'models' => [
    //....
    'role' => App\Models\Role::class, // or use string 'App\\Models\\Role'
    //....
    ],
];

namespace App\Models;

use IsakzhanovR\Permissions\Models\Permission as LaravelPermission;

final class Permission extends LaravelPermission
{
        protected $fillable = [
            'title',
            'slug',
            'description',
        ];
}

return [
//...
'models' => [
    //....
    'permission' => App\Models\Permission::class,
    //....
    ],
//....
];

final class Permission extends LaravelPermission
{
    ....
    public function posts()
    {
        return $this->morphedByMany(PostType::class, 'permissible', 'permissible');
    }
    ....
}

use IsakzhanovR\Permissions\Models\Permissible as LaravelPermissible;

final class Permissible extends LaravelPermissible
{

}

return [
//...
    'models' => [
        //....
        "permissible" => App\Models\Permissible::class,
        //....
    ],
];

    use \App\Models\Role;
    $admin = new Role();
    $admin->slug  = 'admin';
    $admin->title = 'Administrator';
    $admin->description  = 'User is the administrator of a project'; // optional
    $admin->save();

    $manager = new Role();
    $manager->title = 'Project Manager';
    // if you do not specify 'slug' from title 'project-manager' by the method setSlugAttribute()
    $manager->description  = 'User is the manager of a given project'; // optional
    $manager->save();

    use \App\Models\Permission;
    $createPost = new Permission();
    $createPost->title = 'Create Post'; // slug = create-post
    $createPost->save();

    $createNews = new Permission();
    $createNews->title = 'Create News'; // slug = create-news
    $createNews->save();

    $updatePost = new Permission();
    $updatePost->title = 'Update Post'; // slug = update-post
    $updatePost->save();

    $updateNews = new Permission();
    $updateNews->title = 'Update News'; // slug = update-news
    $updateNews->save();

    $updateProfile = new Permission();
    $updateProfile->title = 'Update Profile'; // slug = update-profile
    $updateProfile->save();

    $deletePost = new Permission();
    $deletePost->title = 'Delete Post'; // slug = delete-post
    $deletePost->save();

    $deleteNews = new Permission();
    $deleteNews->title = 'Delete News'; // slug = delete-news
    $deleteNews->save();

use Illuminate\Foundation\Auth\User as Authenticatable;

use IsakzhanovR\Permissions\Traits\HasPermissions;
use IsakzhanovR\Permissions\Traits\HasRoles;
use IsakzhanovR\Permissions\Contracts\PermissibleContract;
use IsakzhanovR\Permissions\Contracts\RoleableContract;

final class User  extends Authenticatable implements PermissibleContract, RoleableContract
{
    use HasRoles, HasPermissions; // add this traits to your user model

    ....
}

    use \App\Models\User;
    $user = User::find(1);

    // abstraction over a method $user->roles()->attach($admin->id)
    $user->attachRole($admin); // parameter can be an Role object, id or slug

    // you can also add multiple user roles
    // equivalent to $user->roles()->sync(array($admin->id, $manager->id));
    $user->attachRoles($admin,$manager,...);

    $user->attachRole(1);                   // id
    //Or
    $user->attachRole('project-manager');   // slug
    //Or
    $user->attachRole(Role::find(1));       // instance of Role

    //Multiple
    $user->attachRoles(1,2,3);
    //Or
    $user->attachRoles('admin','manager','owner');
    //Or
    $user->attachRoles(Role::find(1),Role::find(2),Role::find(3));

    $admin->attachPermissions($createPost,$createNews,$updateProfile);
    $manager->attachPermissions($updatePost,$updateNews);
    $user->attachPermissions($deletePost,$deleteNews);

    $subject->attachPermission(1);                      // id
    //Or
    $subject->attachPermission('create-post');          // slug
    //Or
    $subject->attachPermission(Permission::find(1));    // instance of Permission

    //Multiple
    $subject->attachPermissions(1,'create-post',Permission::find(1),Permission::query()->get());

    $user->detachRole(1);                   // id
    //Or
    $user->detachRole('project-manager');   // slug
    //Or
    $user->detachRole(Role::find(1));       // instance of Role

    //Multiple
    $user->detachRoles(1,'admin',Role::find(1),Role::query()->whereIn('id',[1,2,3])->get());

    $subject->detachPermission(1);                      // id
    //Or
    $subject->detachPermission('create-post');          // slug
    //Or
    $subject->detachPermission(Permission::find(1));    // instance of Permission

    //Multiple
    $subject->detachPermissions(1,2,3);

    $user->syncRoles([1,2,3]);            // array roles ids

    $role->syncPermissions([1,2,3,4]);    //array permissions ids

    $subject->syncPermissions([1,2,3,4]); //array permissions ids

    $user = User::find(1);

    // with role slug:
    $user->hasRole('project-manager'):bool

    // with role id:
    $user->hasRole(1):bool

    // with role instance:
    $user->hasRole(Role::find(1)): bool


    $user = User::find(1);

    // with roles slug, id or instance:
    $user->hasRoles('project-manager',2, Role::find(3)):bool

    // if user has only 'admin' role return false
    $user->hasRoles('project-manager','admin'):bool

    $user = User::find(1);

    // with permission slug or id or instance:
    $subject->hasPermission('create-post'):bool
    // Or use `can`
    $subject->can('create-post'):bool

    // with permission slug, id or instance:
    $user->hasPermissions('create-post',2, Permission::find(3)):bool

    $user = User::find(1);

    // match any create permission:
    $subject->matchPermissions('create*'):bool

    // match any permission about post
    $subject->matchPermissions('*post'):bool


use IsakzhanovR\Permissions\Http\Middleware\Permission;
use IsakzhanovR\Permissions\Http\Middleware\Permissions;
use IsakzhanovR\Permissions\Http\Middleware\Role;
use IsakzhanovR\Permissions\Http\Middleware\Roles;
use IsakzhanovR\Permissions\Http\Middleware\Ability;

protected $routeMiddleware = [
    // ...

    'role'        => Role::class,        // Checks for all of the specified roles.
    'roles'       => Roles::class,       // Checks for the presence of one of the specified roles.
    'permission'  => Permission::class,  // Checks whether all of the specified permissions are entered.
    'permissions' => Permissions::class, // Checks whether one of the specified permissions has been entered.
    'ability'     => Ability::class,     // Checks for matches in both roles and permissions.
]

// Example, user has been a `seo-manager` `project-manager` roles and a `create-post` `update-post` permissions

// success access
app('router')
    ->middleware('role:project-manager,seo-manager', 'permission:create-post,update-post')
    ->get(...)

// failed access because user has not role `admin`
app('router')
    ->middleware('role:project-manager,admin')
    ->get(...)

// failed access because user has not permission `delete-post`
app('router')
    ->middleware('permission:create-post,update-post,delete-post')
    ->get(...)

// Example, user has been a `seo-manager` `project-manager` roles and a `create-post` `update-post` permissions

// success access
app('router')
    ->middleware('ability:*manager')
    ->get(...)

// success access
app('router')
    ->middleware('ability:*post')
    ->get(...)

// failed access because user has not permission `delete` anything
app('router')
    ->middleware('ability:delete*')
    ->get(...)


php artisan vendor:publish --provider="IsakzhanovR\Permissions\ServiceProvider"

php artisan migrate

php artisan laravel-permissions:migrate

Role.php
Permission.php
Permissible.php

php artisan vendor:publish --provider="IsakzhanovR\Permissions\ServiceProvider

php artisan laravel-permissions:create-role {name}

php artisan laravel-permissions:create-permission {name}