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

bouncer

> 后端框架
Open source

Laravel Eloquent roles and abilities.

3.6K stars0 likes0 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](#introduction) - [Installation](#installation) - [Installing Bouncer in a Laravel app](#installing-bouncer-in-a-laravel-app) - [Installing Bouncer in a non-Laravel app](#installing-bouncer-in-a-non-laravel-app) - [Enabling cache](#enabling-cache) - [Usage](#usage) - [Creating roles and abilities](#creating-roles-and-abilities) - [Assigning roles to a user](#assigning-roles-to-a-user) - [Giving a user an ability directly](#giving-a-user-an-ability-directly) - [Restricting an ability to a model](#restricting-an-ability-to-a-model) - [Allowing a user or role to "own" a model](#allowing-a-user-or-role-to-own-a-model) - [Retracting a role from a user](#retracting-a-role-from-a-user) - [Removing an ability](#removing-an-ability) - [Forbidding an ability](#forbidding-an-ability) - [Unforbidding an ability](#unforbidding-an-ability) - [Checking a user's roles](#checking-a-users-roles) - [Querying users by their roles](#querying-users-by-their-roles) - [Getting all roles for a user](#getting-all-roles-for-a-user) - [Getting all abilities for a user](#getting-all-abilities-for-a-user) - [Authorizing users](#authorizing-users) - [Blade directives](#blade-directives) - [Refreshing the cache](#refreshing-the-cache) - [Multi-tenancy](#multi-tenancy) - [The scope middleware](#the-scope-middleware) - [Customizing Bouncer's scope](#customizing-bouncers-scope) - [Configuration](#configuration) - [Cache](#cache) - [Tables](#tables) - [Custom models](#custom-models) - [User Model](#user-model) - [Ownership](#ownership) - [FAQ](#faq) - [Where do I set up my app's roles and abilities?](#where-do-i-set-up-my-apps-roles-and-abilities) - [Can I use a different set of roles & abilities for the public & dashboard sections of my site, respectively?](#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"](#im-trying-to-run-the-migration-but-im-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)"](#im-trying-to-run-the-migration-but-im-getting-a-sql-error-that-there-is-a-syntax-error-or-access-violation-1064--to-use-near-json-not-null) - [Console commands](#console-commands) - [`bouncer:clean`](#bouncerclean) - [Cheat sheet](#cheat-sheet) - [Alternative](#alternative) - [License](#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](#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](https://github.com/JosephSilber/bouncer/tree/v1.0.1). If you're on Laravel v5.5-v5.8, use [Bouncer RC6](https://github.com/JosephSilber/bouncer/tree/v1.0.0-rc.6). ### Installing Bouncer in a Laravel app 1) Install Bouncer with [composer](https://getcomposer.org/doc/00-intro.md): ``` 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](https://laravel.com/docs/11.x/facades). ### Installing Bouncer in a non-Laravel app 1) Install Bouncer with [composer](https://getcomposer.org/doc/00-intro.md): ``` composer require silber/bouncer ``` 2) Set up the database with [the Eloquent Capsule component](https://github.com/illuminate/database/blob/master/README.md): ```php use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule; $capsule->addConnection([/* connection config */]); $capsule->setAsGlobal(); ``` Refer to [the Eloquent Capsule documentation](https://github.com/illuminate/database/blob/master/README.md) for more details. 3) Run the migrations by either of the following methods: - Use a tool such as [vagabond](https://github.com/michaeldyrynda/vagabond) to run Laravel migrations outside of a Laravel app. You'll find the necessary migrations in [the migrations stub file](https://github.com/JosephSilber/bouncer/blob/master/migrations/create_bouncer_tables.php#L18-L79). - Alternatively, you can run [the raw SQL](https://github.com/JosephSilber/bouncer/blob/master/migrations/sql/MySQL.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](https://github.com/JosephSilber/bouncer/blob/c974953a0b1d8d187023002cdfae1800f3ccdb02/src/Factory.php) 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](#configuration) 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](#cache). ## 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](#ownership)). 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 生态主流微服务框架