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

filament-shield

> 后端框架
Open source

The easiest and most intuitive way to add access management to your Filament Panel; Resources, Pages & Widgets through `spatie/laravel-permission`

2.8K stars0 likes2 views
WebsiteGitHub

About

The easiest and most intuitive way to add access management to your Filament Panel; Resources, Pages & Widgets through `spatie/laravel-permission`

Shield

The easiest and most intuitive way to add access management to your Filament panels. > [!IMPORTANT] > This iteration is a complete rewrite from versions 3.x and 4.x-beta and is not backward compatible. Please refer to the [Upgrade](#upgrade) section on how to proceed. ## Features - ️ **Complete Authorization Management** - Resource Permissions - Page Permissions - Widget Permissions - ️ **Custom (ad-hoc) permissions** - **Automatic Policy Generation** - Default Policy methods for Filament Resources - ️ Per Resource Policy definition - Third-party resource policy & permission generation - **Super admin role or gate interception** - **Optional baseline panel user role** - **Multi-tenancy Support** - **Entity discovery** (across all panels if enabled) - **Localized permission & entity labels** - **Seeder generation** (roles + direct permissions) - **Intuitive UI** - ️ Publish & customize the built-in resource - ⚡ **Fine-grained CLI tooling** with safe prohibiting # Installation ## 1. Install Package ```bash composer require bezhansalleh/filament-shield ``` ## 2. Configure Auth Provider 1. Publish the config and set your auth provider model. ```bash php artisan vendor:publish --tag="filament-shield-config" ``` ```php // config/filament-shield.php return [ // ... 'auth_provider_model' => 'App\\Models\\User', // ... ]; ``` 2. Add the `HasRoles` trait to your auth provider model: ```php use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { use HasRoles; } ``` ## 3. Setup Shield Run the setup command (it is interactive and smart): ```bash php artisan shield:setup ``` # Usage & Configuration The package comes with a sensible default configuration that should work for most applications. You can customize the configuration by modifying it to fit your needs. The following sections explain the various configuration options available. ## Permissions You can customize how permission keys are generated to match your preferred naming conventions and organizational standards. Shield uses these settings from the `filament-shield.php` **config** file when creating permission names from your `{Resources|Pages|Widgets}`. ### Configuration ```php 'permissions' => [ 'separator' => ':', 'case' => 'pascal', 'generate' => true, 'format_custom_permission_keys' => true, ], ``` > **Separator & case compatibility:** The separator must not conflict with the case format's own delimiter. Using `_` with `snake`/`lower_snake`/`upper_snake`, or `-` with `kebab`, will throw an `InvalidArgumentException` since it would be impossible to distinguish the affix from the subject in the resulting permission key. ### Case Shield formats permission keys using the specified case style. The available options are: - `camel` - `kebab` - `snake` - `pascal` (default) - `upper_snake` ### Customize permission key composition You can customize how permission keys are generated by providing your own callback to `buildPermissionKeyUsing` in your `AppServiceProvider`'s `boot()` method. The callback receives the following parameters: - `string $entity`: The FQCN of the entity for resources/pages/widgets, or `'custom'` for custom permissions. - `?string $affix`: The action or method name (e.g., 'viewAny', 'create'). `null` for custom permissions. - `string $subject`: The subject or resource name (e.g., 'Post', 'Dashboard'). For custom permissions, this is the raw permission key as defined in config. - `string $case`: The case format specified in the config (e.g., 'pascal'). - `string $separator`: The separator specified in the config (e.g., ':'). Return a `string` to use as the permission key, or `null` to fall back to the default permission key builder. This allows you to selectively override specific entity types while keeping the default behavior for others: * Now let's consider an example where we want to handle `Resource` entities that handle the same `Model` or `Models` with the same name but with different namespaces and directory structures. The Filament [Demo](https://github.com/filamentphp/demo) has two resources with the same name that handle two different models: - `App\Filament\Resources\Blog\Categories\CategoryResource` that handles `App\Models\Blog\Category` - `App\Filament\Resources\Shop\Categories\CategoryResource` that handles `App\Models\Shop\Category` By default Shield will generate the same permission keys for both resources which can cause conflicts. To avoid this we can customize the permission key composition to include the navigation group of the resource as part of the permission key. Here's how you can do it: ``` … ``` Now when you run the `shield:generate` command, it will generate distinct permission keys for each `CategoryResource` based on their navigation groups: - For `Blog`'s `CategoryResource` since its navigation group is `Blog`: - `ViewAny:BlogCategories` - `View:BlogCategories` - `Create:BlogCategories` - `Update:BlogCategories` - `Delete:BlogCategories` - For `Shop`'s `CategoryResource` since it uses a cluster and its navigation group is blank, so it will just use the resource `subject` configured in the config `filament-shield.resources.subject` which is `model` by default: - `ViewAny:Categories` - `View:Categories` - `Create:Categories` - `Update:Categories` - `Delete:Categories` This approach ensures that each resource has a unique set of permission keys, preventing any conflicts and allowing for more granular access control. You can of course extract the logic to a separate class or function if it gets too complex, but this should give you a good starting point. * **Returning `null` for default fallback:** You can return `null` from the closure to let the default builder handle specific entity types. This is useful when you only want to customize certain entities (e.g., custom permissions from Keycloak) while letting everything else use the standard formatting: ```php use BezhanSalleh\FilamentShield\Facades\FilamentShield; FilamentShield::buildPermissionKeyUsing( function (string $entity, ?string $affix, string $subject, string $case, string $separator) { // Custom permissions from external source — use as-is if ($entity === 'custom') { return $subject; } // Everything else uses the default builder return null; } ); ``` ## Policies Shield automatically generates policies for your Resources' Models. ### Configuration ```php 'policies' => [ 'path' => app_path('Policies'), 'merge' => true, 'generate' => true, 'methods' => [ 'viewAny', 'view', 'create', 'update', 'delete', 'deleteAny', 'restore', 'forceDelete', 'forceDeleteAny', 'restoreAny', 'replicate', 'reorder', ], 'single_parameter_methods' => [ 'viewAny', 'create', 'deleteAny', 'forceDeleteAny', 'restoreAny', 'reorder', ], ], ``` ### Policy Placement Shield writes each policy where it belongs for the model that owns it; how policies are resolved at runtime stays in your hands. The rule is applied per model: 1. **Models under `app/Models`** — the policy goes into `policies.path`, keeping any nesting (`app/Models/Blog/Post.php` → `app/Policies/Blog/PostPolicy.php`). 2. **Vendor models** — the policy goes flat into `policies.path`. Shield never writes inside `vendor/`, since Composer wipes it. 3. **Models in any other `Models` directory** (modules, plugins, DDD domains, panel-organized trees) — the policy goes into a sibling `Policies` directory beside the model, exactly where Laravel's policy discovery looks. 4. **Models outside any `Models` directory** (legacy `app/User.php` layouts) — the policy goes flat into `policies.path`. | Model location | Generated policy | Found by Laravel's discovery? | Action needed | |---|---|---|---| | `app/Models/Post.php` (default `policies.path`) | `App\Policies\PostPolicy` | Yes | none | | `app/Models/Blog/Post.php` | `App\Policies\Blog\PostPolicy` | No | `enforcePolicies()` or register | | `app/Models/Post.php` (custom `policies.path`) | e.g. `App\Filament\Policies\PostPolicy` | No | `enforcePolicies()` or register | | `app/Filament/Admin/Models/Post.php` | `App\Filament\Admin\Policies\PostPolicy` | Yes | none | | `modules/Blog/src/Models/Post.php` | `Modules\Blog\Policies\PostPolicy` | Yes | none | | `app/Domain/Users/Models/Post.php` | `App\Domain\Users\Policies\PostPolicy` | Yes | none | | vendor model, no bundled policy | `App\Policies\PostPolicy` | No | `enforcePolicies()` or register (`register_role_policy` already covers Shield's `Role`) | | `app/User.php` (no `Models` directory) | `App\Policies\UserPolicy` | Yes | none | Because the rule is per-model, mixed layouts work with zero configuration: a default `app/Models` tree, an `app-modules/` directory, and vendor models can coexist in one app. Grouping models **inside** `app/Models` (e.g. `app/Models/Shared`, `app/Models/Admin`) mirrors the grouping into your policy tree under `policies.path`; grouping them **outside** it (e.g. `app/Filament/Admin/Models`) yields sibling placement that Laravel discovers on its own — the directory choice selects the trade-off. ### Skipping Provided Policies When a model's policy already resolves to something other than the policy Shield would generate — for example a policy bundled with an installed plugin, or one you registered yourself — `shield:generate` skips that model and reports which policy provides it. Permissions are still generated. Ownership is decided structurally, with two symmetric recipes and no flags: - **Opting a model out** — put your policy anywhere you like, register it with `Gate::policy()`, and delete the file Shield generated. Shield treats it like a plugin-provided policy and backs off that model for good, while still generating its permissions. - **Taking over a provided policy** — create a policy class at Shield's conventional location for the model (see the placement table above), for example with `php artisan make:policy`. Once that class exists, the next `shield:generate` fills it and maintains it from then on. Register it with `Gate::policy()` so it wins over the plugin's — explicit registrations beat discovered ones. The `--ignore-existing-policies` flag is an unrelated axis: it prevents rewriting any policy file that already exists, protecting manual edits. The skip rule decides whether a model is Shield's to generate for; the flag then decides whether an existing file may be rewritten. One caveat: the check runs in the console, so registrations that only happen conditionally at runtime may not be visible while generating. The worst case is an extra generated file that never resolves — Shield itself never registers anything without being asked. ### Methods Each policy includes methods defined in the `policies.methods` config. You can customize this list to fit your ap

GitHub Issues· 0 open

View all on GitHub

No open issues yet, or sync has not completed.

Highlights

  • •️ Complete Authorization Management
  • •Resource Permissions
  • •Page Permissions
  • •Widget Permissions
  • •️ Custom (ad-hoc) permissions
  • •Automatic Policy Generation
  • •Default Policy methods for Filament Resources
  • •️ Per Resource Policy definition
  • •Third-party resource policy & permission generation
  • •Super admin role or gate interception

> Tags

PHPacleasy-access-managementfilamentfilamentplugin

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 生态主流微服务框架