To configure Bouncer to work with multi-tenancy in Laravel, you need to follow these steps:
1. Install Bouncer:
- Run the following command in your terminal to install Bouncer:
bash
composer require silber/bouncer
2. Publish the Scope Middleware:
- Run the following command to publish the scope middleware:
bash
php artisan vendor:publish --tag="bouncer.middleware"
3. Register the Scope Middleware:
- In your `app/Http/Kernel.php` file, add the scope middleware to the `middlewareGroups` array:
php
protected $middlewareGroups = [
'web' => [
// Existing middleware...
\App\Http\Middleware\ScopeBouncer::class,
],
];
4. Configure the Scope Middleware:
- In the `ScopeBouncer` middleware, specify how to determine the current tenant. For example, if you have a `User` model with an `account_id` attribute, you can use this:
php
public function handle($request, Closure $next) {
$tenantId = $request->user()->account_id;
Bouncer::scope()->to($tenantId);
return $next($request);
}
5. Use Bouncer:
- Use Bouncer to manage roles and abilities. For example, you can grant a user the ability to create posts:
php
Bouncer::allow($user)->to('create', Post::class);
6. Scope Abilities:
- Ensure that all Bouncer queries are scoped to the current tenant. This can be done by setting the scope in the middleware:
php
Bouncer::scope()->to($tenantId);
By following these steps, you can integrate Bouncer with Laravel's middleware system to manage roles and abilities for multiple tenants seamlessly[2][3][5].
Citations:[1] https://tenancyforlaravel.com/docs/v3/configuration/
[2] https://packagist.org/packages/natansdj/bouncer
[3] https://github.com/JosephSilber/bouncer
[4] https://laravel-news.com/multi-tenant
[5] https://github.com/JosephSilber/bouncer/issues/217