PHP code example of bbatsche / entrust

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

    

bbatsche / entrust example snippets


'providers' => array(
    'Illuminate\Foundation\Providers\ArtisanServiceProvider',
    'Illuminate\Auth\AuthServiceProvider',
    // ...
    'Bbatsche\Entrust\EntrustServiceProvider',
),

'aliases' => array(
    'App'        => 'Illuminate\Support\Facades\App',
    'Artisan'    => 'Illuminate\Support\Facades\Artisan',
    // ...
    'Entrust'    => 'Bbatsche\Entrust\EntrustFacade',
),



use Bbatsche\Entrust\Contracts\EntrustRoleInterface;
use Bbatsche\Entrust\Traits\EntrustRoleTrait;

class Role extends Eloquent implements EntrustRoleInterface
{
    use EntrustRoleTrait;
}



use Bbatsche\Entrust\Contracts\EntrustPermissionInterface;
use Bbatsche\Entrust\Traits\EntrustPermissionTrait;

class Permission extends Eloquent implements EntrustPermissionInterface
{
    use EntrustPermissionTrait;
}



use Bbatsche\Entrust\Contracts\EntrustUserInterface;
use Bbatsche\Entrust\Traits\EntrustUserTrait;

class User extends Eloquent implements EntrustUserInterface
{
    use EntrustUserTrait;

    ...
}

public function __construct($attr = array())
{
    $this->table = Config::get('entrust::roles_table');

    parent::__construct($attr);
}

public function __construct($attr = array())
{
    $this->table = Config::get('entrust::permissions_table');

    parent::__construct($attr);
}

$role = Role::findOrFail(1); // Pull back a given role

// Regular Delete
$role->delete(); // This will work no matter what

// Force Delete
$role->users()->sync([]); // Delete relationship data
$role->perms()->sync([]); // Delete relationship data

$role->forceDelete(); // Now force delete will work regardless of whether the pivot table has cascading delete

$owner = new Role();
$owner->name         = 'owner';
$owner->display_name = 'Project Owner'; // optional
$owner->description  = 'User is the owner of a given project'; // optional
$owner->save();

$admin = new Role();
$admin->name         = 'admin';
$admin->display_name = 'User Administrator'; // optional
$admin->description  = 'User is allowed to manage and edit other users'; // optional
$admin->save();

$user = User::where('username', '=', 'bbatsche')->first();

// role attach alias
$user->attachRole($admin); // parameter can be an Role object, array, or id

// or eloquent's original technique
$user->roles()->attach($admin->id); // id only

$createPost = new Permission();
$createPost->name         = 'create-post';
$createPost->display_name = 'Create Posts'; // optional
// Allow a user to...
$createPost->description  = 'create new blog posts'; // optional
$createPost->save();

$editUser = new Permission();
$editUser->name         = 'edit-user';
$editUser->display_name = 'Edit Users'; // optional
// Allow a user to...
$editUser->description  = 'edit existing users'; // optional
$editUser->save();

$admin->attachPermission($createPost);
// equivalent to $admin->perms()->attach($createPost->id);

$owner->attachPermissions(array($createPost, $editUser));
// equivalent to $owner->perms()->attach(array($createPost->id, $editUser->id));

$user->is('owner'); // false
$user->is('admin'); // true

$user->isAny(['owner', 'admin']); // true
$user->isAll(['owner', 'admin']); // false, $user does not have the 'owner' role

$failedRoles = array();

$user->isAny(['owner', 'admin'], $failedRoles); // true
// or
$user->isAll(['owner', 'admin'], $failedRoles); // false

print_r($failedRoles);
// Array
// (
//      [0] => owner
// )

$user->can('create-post'); // true
$user->can('edit-user');   // false

$user->canAny(['create-post', 'edit-user']); // true
$user->canAll(['create-post', 'edit-user']); // false, $user doesn't have 'edit-user' permission

$failedPerms = array();

$user->canAny(['create-post', 'edit-user'], $failedPerms); // true
// or
$user->canAll(['create-post', 'edit-user'], $failedPerms); // false

print_r($failedPerms);
// Array
// (
//      [0] => edit-user
// )

Entrust::is('role-name');
Entrust::can('permission-name');

// are identical to

Auth::user()->is('role-name');
Auth::user()->can('permission-name);

Entrust::isAny(['role-name-1', 'role-name-2', /* ... */]);
Entrust::isAll(['role-name-1', 'role-name-2', /* ... */]);

Entrust::canAny(['permission-name-1', 'permission-name-2', /* ... */]);
Entrust::canAll(['permission-name-1', 'permission-name-2', /* ... */]);

// are identical to

Auth::user()->isAny(['role-name-1', 'role-name-2', /* ... */]);
Auth::user()->isAll(['role-name-1', 'role-name-2', /* ... */]);

Auth::user()->canAny(['permission-name-1', 'permission-name-2', /* ... */]);
Auth::user()->canAll(['permission-name-1', 'permission-name-2', /* ... */]);

$user->ability(array('admin', 'owner'), array('create-post', 'edit-user'));

// or

$user->ability('admin,owner', 'create-post,edit-user');

$options = array(
    'validate_all' => true | false (Default: false),
    'return_type'  => boolean | array | both (Default: boolean)
);

$options = array(
    'validate_all' => true,
    'return_type' => 'both'
);

list($validate, $allValidations) = $user->ability(
    array('admin', 'owner'),
    array('create-post', 'edit-user'),
    $options
);

var_dump($validate);
// bool(false)

var_dump($allValidations);
// array(4) {
//     ['role'] => bool(true)
//     ['role_2'] => bool(false)
//     ['create-post'] => bool(true)
//     ['edit-user'] => bool(false)
// }



use Bbatsche\Entrust\Traits\EntrustControllerTrait;

class BaseController extends Controller
{
    use EntrustControllerTrait;
}

public function __construct()
{
    $this->beforeFilter('@entrustRoleFilter');

    // and / or

    $this->beforeFilter('@entrustPermissionFilter');
}

protected $entrustPerms = array(
    'create'  => 'post-create',
    'edit'    => ['post-edit-own',    'post-edit'],
    'destroy' => ['post-destroy-own', 'post-destroy']
);

protected $entrustRoles = array(
    'index'  => ['owner', 'admin'],
    'store'  => 'owner',
    'update' => 'owner'
);

public function entrustPermissionCallback($method, $failedPerms, $allPerms)
{
    if (empty($allPerms)) {
        // No perms defined but filter still failed, meaning user was not authenticated
        App::abort(401, 'You do not have permission to view this page, please log in.');
    }

    // Empty failed perms means user was not authenticated
    // Act as if *all* perms failed instead
    $failedPerms = $failedPerms ?: $allPerms;

    $join = $this->entrustRequireAll ? 'and' : 'or';

    $desc = Permission::whereIn('name', (array)$failedPerms)->lists('description');

    switch (count($desc)) {
        case 1:
            $message = "You do not have permission to {$desc[0]}!";
            break;
        case 2:
            $message = "You do not have permission to {$desc[0]} $join {$desc[1]}!";
            break;
        default:
            $last = array_pop($desc);

            $message = 'You do not have permission to ' . implode(', ', $desc) . ", $join $last!";
            break;
    }

    App::abort(403, $message);
}

// only users with roles that have the 'manage_posts' permission will be able to access any route within admin/post
Entrust::routeNeedsPermission('admin/post*', 'create-post');

// only owners will have access to routes within admin/advanced
Entrust::routeNeedsRole('admin/advanced*', 'owner');

// optionally the second parameter can be an array of permissions or roles
// user would need to match all roles or permissions for that route
Entrust::routeNeedsPermission('admin/post*', array('create-post', 'edit-comment'));
Entrust::routeNeedsRole('admin/advanced*', array('owner','writer'));

Entrust::routeNeedsRole('admin/advanced*', 'owner', Redirect::to('/home'));

// if a user has 'create-post', 'edit-comment', or both they will have access
Entrust::routeNeedsPermission('admin/post*', array('create-post', 'edit-comment'), null, false);

// if a user is a member of 'owner', 'writer', or both they will have access
Entrust::routeNeedsRole('admin/advanced*', array('owner','writer'), null, false);

// if a user is a member of 'owner', 'writer', or both, or user has 'create-post', 'edit-comment' they will have access
// if the 4th parameter is true then the user must be a member of Role and must have Permission
Entrust::routeNeedsRoleOrPermission(
    'admin/advanced*',
    array('owner', 'writer'),
    array('create-post', 'edit-comment'),
    null,
    false
);

Route::filter('manage_posts', function()
{
    // check the current user
    if (!Entrust::can('create-post')) {
        return Redirect::to('admin');
    }
});

// only users with roles that have the 'manage_posts' permission will be able to access any admin/post route
Route::when('admin/post*', 'manage_posts');

Route::filter('owner_role', function()
{
    // check the current user
    if (!Entrust::hasRole('Owner')) {
        App::abort(403);
    }
});

// only owners will have access to routes within admin/advanced
Route::when('admin/advanced*', 'owner_role');
bash
php artisan config:publish bbatsche/entrust
bash
php artisan entrust:migration
bash
php artisan migrate
bash
composer dump-autoload