PHP code example of silber / bouncer

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

    

silber / bouncer example snippets


// Give a user the ability to create posts
Bouncer::allow($user)->to('create', Post::class);

// Alternatively, do it through a role
Bouncer::allow('admin')->to('create', Post::class);
Bouncer::assign('admin')->to($user);

// You can also grant an ability only to a specific model
Bouncer::allow($user)->to('edit', $post);

    use Silber\Bouncer\Database\HasRolesAndAbilities;

    class User extends Model
    {
        use HasRolesAndAbilities;
    }
    

use Bouncer;

    use Illuminate\Database\Capsule\Manager as Capsule;

    $capsule = new Capsule;

    $capsule->addConnection([/* connection config */]);

    $capsule->setAsGlobal();
    

    use Illuminate\Database\Eloquent\Model;
    use Silber\Bouncer\Database\HasRolesAndAbilities;

    class User extends Model
    {
        use HasRolesAndAbilities;
    }
    

    use Silber\Bouncer\Bouncer;

    $bouncer = Bouncer::create();

    // If you are in a request with a current user
    // that you'd wish to check permissions for,
    // pass that user to the "create" method:
    $bouncer = Bouncer::create($user);
    

    use Silber\Bouncer\Bouncer;
    use Illuminate\Container\Container;

    Container::getInstance()->singleton(Bouncer::class, function () {
        return Bouncer::create();
    });
    

    use Silber\Bouncer\Bouncer;

    $bouncer = Bouncer::make()
             ->withCache($customCacheInstance)
             ->create();
    

    $bouncer->useUserModel(User::class);
    

Bouncer::allow('admin')->to('ban-users');

$admin = Bouncer::role()->firstOrCreate([
    'name' => 'admin',
    'title' => 'Administrator',
]);

$ban = Bouncer::ability()->firstOrCreate([
    'name' => 'ban-users',
    'title' => 'Ban users',
]);

Bouncer::allow($admin)->to($ban);

Bouncer::assign('admin')->to($user);

$user->assign('admin');

Bouncer::allow($user)->to('ban-users');

$user->allow('ban-users');

Bouncer::allow($user)->to('edit', Post::class);

Bouncer::allow($user)->to('edit', $post);

Bouncer::allow($user)->toOwn(Post::class);

Bouncer::allow($user)->toOwn(Post::class)->to('view');

// Or pass it an array of abilities:
Bouncer::allow($user)->toOwn(Post::class)->to(['view', 'update']);

Bouncer::allow($user)->toOwnEverything();

// And to restrict ownership to a given ability
Bouncer::allow($user)->toOwnEverything()->to('view');

Bouncer::retract('admin')->from($user);

$user->retract('admin');

Bouncer::disallow($user)->to('ban-users');

$user->disallow('ban-users');

Bouncer::disallow('admin')->to('ban-users');

Bouncer::disallow($user)->to('delete', Post::class);

Bouncer::disallow($user)->to('delete', $post);

    Bouncer::allow($user)->to('view', Document::class);

    Bouncer::forbid($user)->to('view', $classifiedDocument);
    

    Bouncer::allow('superadmin')->everything();

    Bouncer::allow('admin')->everything();
    Bouncer::forbid('admin')->toManage(User::class);
    

    Bouncer::forbid('banned')->everything();
    

    Bouncer::assign('banned')->to($user);
    

    Bouncer::retract('banned')->from($user);
    

Bouncer::unforbid($user)->to('view', $classifiedDocument);

Bouncer::is($user)->a('moderator');

Bouncer::is($user)->an('admin');

Bouncer::is($user)->notA('moderator');

Bouncer::is($user)->notAn('admin');

Bouncer::is($user)->a('moderator', 'editor');

Bouncer::is($user)->all('editor', 'moderator');

Bouncer::is($user)->notAn('editor', 'moderator');

$user->isAn('admin');
$user->isA('subscriber');

$user->isNotAn('admin');
$user->isNotA('subscriber');

$user->isAll('editor', 'moderator');

$users = User::whereIs('admin')->get();

$users = User::whereIs('superadmin', 'admin')->get();

$users = User::whereIsAll('sales', 'marketing')->get();

$roles = $user->getRoles();

$abilities = $user->getAbilities();

$forbiddenAbilities = $user->getForbiddenAbilities();

Bouncer::can($ability);
Bouncer::can($ability, $model);

Bouncer::canAny($abilities);
Bouncer::canAny($abilities, $model);

Bouncer::cannot($ability);
Bouncer::cannot($ability, $model);

Bouncer::authorize($ability);
Bouncer::authorize($ability, $model);

@if ($user->isAn('admin'))
    //
@endif

Bouncer::refresh();

Bouncer::refreshFor($user);

public function handle($request, Closure $next)
{
    $tenantId = $request->user()->account_id;

    Bouncer::scope()->to($tenantId);

    return $next($request);
}

protected $middlewareGroups = [
    'web' => [
        // Keep the existing middleware here, and add this:
        \App\Http\Middleware\ScopeBouncer::class,
    ]
];

Bouncer::scope()->to($tenantId)->onlyRelations();

Bouncer::scope()->to($tenantId)->onlyRelations()->dontScopeRoleAbilities();

use Silber\Bouncer\Contracts\Scope;

class MyScope implements Scope
{
    // Whatever custom logic your app needs
}

Bouncer::scope(new MyScope);

Bouncer::cache();

Bouncer::dontCache();

Bouncer::tables([
    'abilities' => 'my_abilities',
    'permissions' => 'granted_abilities',
]);

namespace App\Models;

use Silber\Bouncer\Database\Ability as BouncerAbility;

class Ability extends BouncerAbility
{
    // custom code
}

namespace App\Models;

use Silber\Bouncer\Database\Role as BouncerRole;

class Role extends BouncerRole
{
    // custom code
}

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Silber\Bouncer\Database\Concerns\IsAbility;

class Ability extends Model
{
    use IsAbility;

    // custom code
}

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Silber\Bouncer\Database\Concerns\IsRole;

class Role extends Model
{
    use IsRole;

    // custom code
}

Bouncer::useAbilityModel(\App\Models\Ability::class);
Bouncer::useRoleModel(\App\Models\Role::class);

Bouncer::useUserModel(\App\Admin::class);

Bouncer::ownedVia('userId');

Bouncer::ownedVia(Post::class, 'created_by');
Bouncer::ownedVia(Order::class, 'entered_by');

Bouncer::ownedVia(Game::class, function ($game, $user) {
    return $game->team_id == $user->team_id;
});

use Bouncer;
use Illuminate\Database\Seeder;

class BouncerSeeder extends Seeder
{
    public function run()
    {
        Bouncer::allow('superadmin')->everything();

        Bouncer::allow('admin')->everything();
        Bouncer::forbid('admin')->toManage(User::class);

        Bouncer::allow('editor')->to('create', Post::class);
        Bouncer::allow('editor')->toOwn(Post::class);

        // etc.
    }
}

    use Bouncer, Closure;

    class ScopeBouncer
    {
        public function handle($request, Closure $next, $identifier)
        {
            Bouncer::scope()->to($identifier);

            return $next($request);
        }
    }
    

    protected $routeMiddleware = [
        // Keep the other route middleware, and add this:
        'scope-bouncer' => \App\Http\Middleware\ScopeBouncer::class,
    ];
    

    Route::middleware(['web', 'scope-bouncer:1'])
         ->namespace($this->namespace)
         ->group(base_path('routes/public.php'));

    Route::middleware(['web', 'scope-bouncer:2'])
         ->namespace($this->namespace)
         ->group(base_path('routes/dashboard.php'));
    

use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

    Bouncer::allow($user)->to('view', Plan::class);

    Bouncer::disallow($user)->to('view', Plan::class);
    

    Bouncer::allow($user)->to('delete', $plan);

    $plan->delete();
    

$schedule->command('bouncer:clean')->weekly();

// Adding abilities for users
Bouncer::allow($user)->to('ban-users');
Bouncer::allow($user)->to('edit', Post::class);
Bouncer::allow($user)->to('delete', $post);

Bouncer::allow($user)->everything();
Bouncer::allow($user)->toManage(Post::class);
Bouncer::allow($user)->toManage($post);
Bouncer::allow($user)->to('view')->everything();

Bouncer::allow($user)->toOwn(Post::class);
Bouncer::allow($user)->toOwnEverything();

// Removing abilities uses the same syntax, e.g.
Bouncer::disallow($user)->to('delete', $post);
Bouncer::disallow($user)->toManage(Post::class);
Bouncer::disallow($user)->toOwn(Post::class);

// Adding & removing abilities for roles
Bouncer::allow('admin')->to('ban-users');
Bouncer::disallow('admin')->to('ban-users');

// You can also forbid specific abilities with the same syntax...
Bouncer::forbid($user)->to('delete', $post);

// And also remove a forbidden ability with the same syntax...
Bouncer::unforbid($user)->to('delete', $post);

// Re-syncing a user's abilities
Bouncer::sync($user)->abilities($abilities);

// Assigning & retracting roles from users
Bouncer::assign('admin')->to($user);
Bouncer::retract('admin')->from($user);

// Assigning roles to multiple users by ID
Bouncer::assign('admin')->to([1, 2, 3]);

// Re-syncing a user's roles
Bouncer::sync($user)->roles($roles);

// Checking the current user's abilities
$boolean = Bouncer::can('ban-users');
$boolean = Bouncer::can('edit', Post::class);
$boolean = Bouncer::can('delete', $post);

$boolean = Bouncer::cannot('ban-users');
$boolean = Bouncer::cannot('edit', Post::class);
$boolean = Bouncer::cannot('delete', $post);

// Checking a user's roles
$boolean = Bouncer::is($user)->a('subscriber');
$boolean = Bouncer::is($user)->an('admin');
$boolean = Bouncer::is($user)->notA('subscriber');
$boolean = Bouncer::is($user)->notAn('admin');
$boolean = Bouncer::is($user)->a('moderator', 'editor');
$boolean = Bouncer::is($user)->all('moderator', 'editor');

Bouncer::cache();
Bouncer::dontCache();

Bouncer::refresh();
Bouncer::refreshFor($user);

$user->allow('ban-users');
$user->allow('edit', Post::class);
$user->allow('delete', $post);

$user->disallow('ban-users');
$user->disallow('edit', Post::class);
$user->disallow('delete', $post);

$user->assign('admin');
$user->retract('admin');

$boolean = $user->isAn('admin');
$boolean = $user->isAn('editor', 'moderator');
$boolean = $user->isAll('moderator', 'editor');
$boolean = $user->isNotAn('admin', 'moderator');

// Querying users by their roles
$users = User::whereIs('superadmin')->get();
$users = User::whereIs('superadmin', 'admin')->get();
$users = User::whereIsAll('sales', 'marketing')->get();

$abilities = $user->getAbilities();
$forbidden = $user->getForbiddenAbilities();

    php artisan vendor:publish --tag="bouncer.migrations"
    

    php artisan migrate
    

php artisan vendor:publish --tag="bouncer.middleware"

php artisan make:seeder BouncerSeeder

php artisan db:seed --class=BouncerSeeder

php artisan bouncer:clean --unassigned
php artisan bouncer:clean --orphaned