PHP code example of dadansatria / laravel-permission-mongodb

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

    

dadansatria / laravel-permission-mongodb example snippets


// Adding permissions to a user
$user->givePermissionTo('edit articles');

// Adding permissions via a role
$user->assignRole('writer');

$role->givePermissionTo('edit articles');

$user->can('edit articles');

return [

    'models' => [

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * Moloquent model should be used to retrieve your permissions. Of course, it
         * is often just the "Permission" model but you may use whatever you like.
         *
         * The model you want to use as a Permission model needs to implement the
         * `Dadansatria\Permission\Contracts\Permission` contract.
         */

        'permission' => Dadansatria\Permission\Models\Permission::class,

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * Moloquent model should be used to retrieve your roles. Of course, it
         * is often just the "Role" model but you may use whatever you like.
         *
         * The model you want to use as a Role model needs to implement the
         * `Dadansatria\Permission\Contracts\Role` contract.
         */

        'role' => Dadansatria\Permission\Models\Role::class,

    ],

    'collection_names' => [

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your roles. We have chosen a basic
         * default value but you may easily change it to any table you like.
         */

        'roles' => 'roles',

        /*
         * When using the "HasRoles" trait from this package, we need to know which
         * table should be used to retrieve your permissions. We have chosen a basic
         * default value but you may easily change it to any table you like.
         */

        'permissions' => 'permissions',
    ],

    /*
     * By default all permissions will be cached for 24 hours unless a permission or
     * role is updated. Then the cache will be flushed immediately.
     */

    'cache_expiration_time' => 60 * 24,

    /*
     * By default we'll make an entry in the application log when the permissions
     * could not be loaded. Normally this only occurs while installing the packages.
     *
     * If for some reason you want to disable that logging, set this value to false.
     */

    'log_registration_exception' => true,
    
    /*
     * When set to true, the 

$app->routeMiddleware([
    'auth'       => App\Http\Middleware\Authenticate::class,
    'permission' => Dadansatria\Permission\Middlewares\PermissionMiddleware::class,
    'role'       => Dadansatria\Permission\Middlewares\RoleMiddleware::class,
]);

$app->configure('permission');
$app->register(Dadansatria\Permission\PermissionServiceProvider::class);

use Illuminate\Auth\Authenticatable;
use MongoDB\Laravel\Eloquent\Model as Model;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Dadansatria\Permission\Traits\HasRoles;

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable, HasRoles;

    // ...
}

use MongoDB\Laravel\Eloquent\Model as Model;
use Dadansatria\Permission\Traits\HasRoles;

class Page extends Model
{
    use HasRoles;

    protected $guard_name = 'web'; // or whatever guard you want to use

    // ...
}

use Dadansatria\Permission\Models\Role;
use Dadansatria\Permission\Models\Permission;

$role = Role::create(['name' => 'writer']);
$permission = Permission::create(['name' => 'edit articles']);

$role->givePermissionTo($permission);
$permission->assignRole($role);

$role->syncPermissions($permissions);
$permission->syncRoles($roles);

$role->revokePermissionTo($permission);
$permission->removeRole($role);

// get a list of all permissions directly assigned to the user
$permissions = $user->permissions; // Returns a collection

// get all permissions inherited by the user via roles
$permissions = $user->getAllPermissions(); // Returns a collection

// get all permissions names
$permissions = $user->getPermissionNames(); // Returns a collection

// get a collection of all defined roles
$roles = $user->roles->pluck('name'); // Returns a collection

// get all role names
$roles = $user->getRoleNames() // Returns a collection;

$users = User::role('writer')->get(); // Returns only users with the role 'writer'
$users = User::permission('edit articles')->get(); // Returns only users with the permission 'edit articles'

$user->givePermissionTo('edit articles');

// You can also give multiple permission at once
$user->givePermissionTo('edit articles', 'delete articles');

// You may also pass an array
$user->givePermissionTo(['edit articles', 'delete articles']);

$user->revokePermissionTo('edit articles');

$user->syncPermissions(['edit articles', 'delete articles']);

$user->hasPermissionTo('edit articles');

$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);

$user->can('edit articles');

$user->assignRole('writer');

// You can also assign multiple roles at once
$user->assignRole('writer', 'admin');
// or as an array
$user->assignRole(['writer', 'admin']);

$user->removeRole('writer');

// All current roles will be removed from the user and replaced by the array given
$user->syncRoles(['writer', 'admin']);

$user->hasRole('writer');

$user->hasAnyRole(Role::all());

$user->hasAllRoles(Role::all());

$role->givePermissionTo('edit articles');

$role->hasPermissionTo('edit articles');

$role->revokePermissionTo('edit articles');

$role = Role::findByName('writer');
$role->givePermissionTo('edit articles');

$user->assignRole('writer');

$user->givePermissionTo('delete articles');

// Direct permissions
$user->getDirectPermissions() // Or $user->permissions;

// Permissions inherited from the user's roles
$user->getPermissionsViaRoles();

// All permissions which apply on the user (inherited and direct)
$user->getAllPermissions();

@role('writer')
    I am a writer!
@else
    I am not a writer...
@endrole

@hasrole('writer')
    I am a writer!
@else
    I am not a writer...
@endhasrole

@hasanyrole(Role::all())
    I have one or more of these roles!
@else
    I have none of these roles...
@endhasanyrole
// or
@hasanyrole('writer|admin')
    I am either a writer or an admin or both!
@else
    I have none of these roles...
@endhasanyrole

@hasallroles(Role::all())
    I have all of these roles!
@else
    I do not have all of these roles...
@endhasallroles
// or
@hasallroles('writer|admin')
    I am both a writer and an admin!
@else
    I do not have all of these roles...
@endhasallroles

@can('edit articles')
  //
@endcan

@if(auth()->user()->can('edit articles') && $some_other_condition)
  //
@endif

// Create a superadmin role for the admin users

$user->hasPermissionTo('publish articles', 'admin');

@role('super-admin', 'admin')
    I am a super-admin!
@else
    I am not a super-admin...
@endrole

protected $routeMiddleware = [
    // ...
    'role' => \Dadansatria\Permission\Middlewares\RoleMiddleware::class,
    'permission' => \Dadansatria\Permission\Middlewares\PermissionMiddleware::class,
];

Route::group(['middleware' => ['role:super-admin']], function () {
    //
});

Route::group(['middleware' => ['permission:publish articles']], function () {
    //
});

Route::group(['middleware' => ['role:super-admin','permission:publish articles']], function () {
    //
});

public function __construct()
{
    $this->middleware(['role:super-admin','permission:publish articles|edit articles']);
}

public function render($request, Exception $exception)
{
    if ($exception instanceof \Dadansatria\Permission\Exceptions\UnauthorizedException) {
        // Code here ...
    }

    return parent::render($request, $exception);
}


public function setUp()
{
    // first gister all the roles and permissions
    $this->app->make(\Dadansatria\Permission\PermissionRegistrar::class)->registerPermissions();
}

use Illuminate\Database\Seeder;
use Dadansatria\Permission\Models\Role;
use Dadansatria\Permission\Models\Permission;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // Reset cached roles and permissions
        app()['cache']->forget('maklad.permission.cache');
        
        // create permissions
        Permission::firstOrCreate(['name' => 'edit articles']);
        Permission::firstOrCreate(['name' => 'delete articles']);
        Permission::firstOrCreate(['name' => 'publish articles']);
        Permission::firstOrCreate(['name' => 'unpublish articles']);
        
        // create roles and assign existing permissions
        $role = Role::firstOrCreate(['name' => 'writer']);
        $role->givePermissionTo('edit articles');
        $role->givePermissionTo('delete articles');
        
        $role = Role::firstOrCreate(['name' => 'admin']);
        $role->givePermissionTo(['publish articles', 'unpublish articles']);
    }
}

$user->assignRole('writer');
$user->removeRole('writer');
$user->syncRoles(params);
$role->givePermissionTo('edit articles');
$role->revokePermissionTo('edit articles');
$role->syncPermissions(params);
$permission->assignRole('writer');
$permission->removeRole('writer');
$permission->syncRoles(params);
bash
php artisan vendor:publish --provider="Dadansatria\Permission\PermissionServiceProvider" --tag="migrations"
bash
php artisan migrate
bash
php artisan vendor:publish --provider="Dadansatria\Permission\PermissionServiceProvider" --tag="config"
bash
cp vendor/mostafamaklad/laravel-permission-mongodb/config/permission.php config/permission.php
cp vendor/mostafamaklad/laravel-permission-mongodb/database/migrations/create_permission_collections.php.stub database/migrations/2018_01_01_000000_create_permission_collections.php
bash
curl -Ls https://raw.githubusercontent.com/laravel/lumen-framework/5.5/config/auth.php -o config/auth.php
bash
php artisan migrate
bash
php artisan permission:create-permission 'edit articles'
bash
php artisan permission:create-permission 'edit articles' web
bash
  php artisan vendor:publish --provider="Dadansatria\Permission\PermissionServiceProvider" --tag="config"
  
bash
php artisan cache:forget maklad.permission.cache