Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
B

bouncer

> 后端框架
Open source

Laravel Eloquent roles and abilities.

3.6K stars0 likes1 views
WebsiteGitHub

About

Laravel Eloquent roles and abilities.

Bouncer

Bouncer is an elegant, framework-agnostic approach to managing roles and abilities for any app using Eloquent models.

Table of Contents

Click to expand

  • Introduction
  • Installation
    • Installing Bouncer in a Laravel app
    • Installing Bouncer in a non-Laravel app
    • Enabling cache
  • Usage
    • Creating roles and abilities
    • Assigning roles to a user
    • Giving a user an ability directly
    • Restricting an ability to a model
    • Allowing a user or role to "own" a model
    • Retracting a role from a user
    • Removing an ability
    • Forbidding an ability
    • Unforbidding an ability
    • Checking a user's roles
    • Querying users by their roles
    • Getting all roles for a user
    • Getting all abilities for a user
    • Authorizing users
    • Blade directives
    • Refreshing the cache
  • Multi-tenancy
    • The scope middleware
    • Customizing Bouncer's scope
  • Configuration
    • Cache
    • Tables
    • Custom models
    • User Model
    • Ownership
  • FAQ
    • Where do I set up my app's roles and abilities?
    • Can I use a different set of roles & abilities for the public & dashboard sections of my site, respectively?
    • I'm trying to run the migration, but I'm getting a SQL error that the "specified key was too long"
    • I'm trying to run the migration, but I'm getting a SQL error that there is a "Syntax error or access violation: 1064 ... to use near json not null)"
  • Console commands
    • bouncer:clean
  • Cheat sheet
  • Alternative
  • License

Introduction

Bouncer is an elegant, framework-agnostic approach to managing roles and abilities for any app using Eloquent models. With an expressive and fluent syntax, it stays out of your way as much as possible: use it when you want, ignore it when you don't.

For a quick, glanceable list of Bouncer's features, check out the cheat sheet.

Bouncer works well with other abilities you have hard-coded in your own app. Your code always takes precedence: if your code allows an action, Bouncer will not interfere.

Once installed, you can simply tell the bouncer what you want to allow at the gate:

php
// 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);

When you check abilities at Laravel's gate, Bouncer will automatically be consulted. If Bouncer sees an ability that has been granted to the current user (whether directly, or through a role) it'll authorize the check.

Installation

Note: Bouncer v1.0.2 requires PHP 8.2+ and Laravel/Eloquent 11+.

If you're on Laravel v6-v10, use Bouncer v1.0.1. If you're on Laravel v5.5-v5.8, use Bouncer RC6.

Installing Bouncer in a Laravel app

  1. Install Bouncer with composer:

    composer require silber/bouncer
  2. Add Bouncer's trait to your user model:

    php
    use Silber\Bouncer\Database\HasRolesAndAbilities;
    
    class User extends Model
    {
        use HasRolesAndAbilities;
    }
  3. Now, to run Bouncer's migrations. First publish the migrations into your app's migrations directory, by running the following command:

    php artisan vendor:publish --tag="bouncer.migrations"
  4. Finally, run the migrations:

    php artisan migrate

Facade

Whenever you use the Bouncer facade in your code, remember to add this line to your namespace imports at the top of the file:

php
use Bouncer;

For more information about Laravel Facades, refer to the Laravel documentation.

Installing Bouncer in a non-Laravel app

  1. Install Bouncer with composer:

    composer require silber/bouncer
  2. Set up the database with the Eloquent Capsule component:

    php
    use Illuminate\Database\Capsule\Manager as Capsule;
    
    $capsule = new Capsule;
    
    $capsule->addConnection([/* connection config */]);
    
    $capsule->setAsGlobal();

    Refer to the Eloquent Capsule documentation for more details.

  3. Run the migrations by either of the following methods:

    • Use a tool such as vagabond to run Laravel migrations outside of a Laravel app. You'll find the necessary migrations in the migrations stub file.

    • Alternatively, you can run the raw SQL directly in your database.

  4. Add Bouncer's trait to your user model:

    php
    use Illuminate\Database\Eloquent\Model;
    use Silber\Bouncer\Database\HasRolesAndAbilities;
    
    class User extends Model
    {
        use HasRolesAndAbilities;
    }
  5. Create an instance of Bouncer:

    php
    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);

    If you're using dependency injection in your app, you may register the Bouncer instance as a singleton in the container:

    php
    use Silber\Bouncer\Bouncer;
    use Illuminate\Container\Container;
    
    Container::getInstance()->singleton(Bouncer::class, function () {
        return Bouncer::create();
    });

    You can now inject Bouncer into any class that needs it.

    The create method creates a Bouncer instance with sensible defaults. To fully customize it, use the make method to get a factory instance. Call create() on the factory to create the Bouncer instance:

    php
    use Silber\Bouncer\Bouncer;
    
    $bouncer = Bouncer::make()
             ->withCache($customCacheInstance)
             ->create();

    Check out the Factory class to see all the customizations available.

  6. Set which model is used as the user model throughout your app:

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

    For additional configuration, check out the Configuration section below.

Enabling cache

By default, Bouncer's queries are cached for the current request. For better performance, you may want to enable cross-request caching.

Usage

Adding roles and abilities to users is made extremely easy. You do not have to create a role or an ability in advance. Simply pass the name of the role/ability, and Bouncer will create it if it doesn't exist.

Note: the examples below all use the Bouncer facade. If you don't use facades, you can instead inject an instance of Silber\Bouncer\Bouncer into your class.

Creating roles and abilities

Let's create a role called admin and give it the ability to ban-users from our site:

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

That's it. Behind the scenes, Bouncer will create both a Role model and an Ability model for you.

If you want to add additional attributes to the role/ability, such as a human-readable title, you can manually create them using the role and ability methods on the Bouncer class:

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

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

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

Assigning roles to a user

To now give the admin role to a user, simply tell the bouncer that the given user should be assigned the admin role:

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

Alternatively, you can call the assign method directly on the user:

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

Giving a user an ability directly

Sometimes you might want to give a user an ability directly, without using a role:

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

Here too you can accomplish the same directly off of the user:

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

Restricting an ability to a model

Sometimes you might want to restrict an ability to a specific model type. Simply pass the model name as a second argument:

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

If you want to restrict the ability to a specific model instance, pass in the actual model instead:

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

Allowing a user or role to "own" a model

Use the toOwn method to allow users to manage their own models:

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

Now, when checking at the gate whether the user may perform an action on a given post, the post's user_id will be compared to the logged-in user's id (this can be customized). If they match, the gate will allow the action.

The above will grant all abilities on a user's "owned" models. You can restrict the abilities by following it up with a call to the to method:

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

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

You can also allow users to own all types of models in your application:

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

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

Retracting a role from a user

The bouncer can also retract a previously-assigned role from a user:

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

Or do it directly on the user:

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

Removing an ability

The bouncer can also remove an ability previously granted to a user:

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

Or directly on the user:

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

Note: if the user has a role that allows them to `ba

Issues· 53 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPaclauthauthorizationeloquent

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架