Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can Bouncer integrate seamlessly with Laravel's middleware system
    Laravel Bouncer


Can Bouncer integrate seamlessly with Laravel's middleware system


Yes, Bouncer integrates seamlessly with Laravel's middleware system. Here are some key points on how Bouncer integrates with Laravel's middleware:

1. Scope Middleware: Bouncer provides a middleware called `ScopeBouncer` that allows you to specify the tenant ID for the current request. This middleware is published to `app/Http/Middleware/ScopeBouncer.php` and needs to be registered in the HTTP kernel. This ensures that all Bouncer queries are scoped to the correct tenant[1].

2. Middleware Registration: To use the `ScopeBouncer` middleware, you need to register it in the HTTP kernel. This is done by adding the middleware to the `middlewareGroups` array in the `Kernel.php` file. For example:

php
   protected $middlewareGroups = [
       'web' => [
           // Existing middleware...
           \App\Http\Middleware\ScopeBouncer::class,
       ],
   ];
   

3. Middleware Usage: The `ScopeBouncer` middleware is used to specify the tenant ID for the current request. For example, if you have a `User` model with an `account_id` attribute, you can use the middleware to set the tenant ID:

php
   public function handle($request, Closure $next) {
       $tenantId = $request->user()->account_id;
       Bouncer::scope()->to($tenantId);
       return $next($request);
   }
   

4. Integration with Laravel's Gate: Bouncer integrates with Laravel's authorization gate, allowing you to use the `@can` directive in your Blade templates. When you check abilities at Laravel's gate, Bouncer will automatically be consulted to authorize the check if the ability has been granted to the current user[1][3].

By integrating with Laravel's middleware system and gate, Bouncer provides a seamless and efficient way to manage roles and permissions in your Laravel application.

Citations:
[1] https://github.com/JosephSilber/bouncer
[2] https://josephsilber.com/posts/2022/05/17/releasing-bouncer-laravel-roles-and-permissions
[3] https://laravel-news.com/bouncer-authorization-package
[4] https://madewithlaravel.com/bouncer
[5] https://laravel-news.com/two-best-roles-permissions-packages