PHP code example of bezhansalleh / filament-shield

1. Go to this page and download the library: Download bezhansalleh/filament-shield library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bezhansalleh / filament-shield example snippets


   // config/filament-shield.php
   return [
       // ...
       'auth_provider_model' => 'App\\Models\\User',
       // ...
   ];
   

   use Spatie\Permission\Traits\HasRoles;

   class User extends Authenticatable
   {
       use HasRoles;
   }
   

'permissions' => [
    'separator' => ':',
    'case' => 'pascal',
    'generate' => true,
],

  use BezhanSalleh\FilamentShield\Facades\FilamentShield;
  use Filament\Resources\Resource;

  FilamentShield::buildPermissionKeyUsing(
      function (string $entity, string $affix, string $subject, string $case, string $separator) {
        if (is_subclass_of($entity, Resource::class) && in_array(
              needle: $entity, 
              haystack: [
                  'App\Filament\Resources\Blog\Categories\CategoryResource',
                  'App\Filament\Resources\Shop\Categories\CategoryResource'
              ],
              strict: true
        )) {
            $subject = str($subject)
                ->prepend($resource::getNavigationGroup())
                ->trim()
                ->toString();
        }

        return FilamentShield::defaultPermissionKeyBuilder(
            affix: $affix, 
            separator: $separator, 
            subject: $subject, 
            case: $case
        );
    }
  );
  

'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',
    ],
],

Gate::policy(Awcodes\Curator\Models\Media::class, App\Policies\MediaPolicy::class);

use Illuminate\Support\Facades\Gate;

Gate::guessPolicyNamesUsing(function (string $modelClass) {
    return str_replace('Models', 'Policies', $modelClass) . 'Policy';
});

'resources' => [
    'subject' => 'model',
    'manage' => [
        \BezhanSalleh\FilamentShield\Resources\Roles\RoleResource::class => [
            'viewAny',
            'view',
            'create',
            'update',
            'delete',
        ],
    ],
    'exclude' => [
        //
    ],
],

'pages' => [
    'subject' => 'class',
    'prefix' => 'view',
    'exclude' => [
        \Filament\Pages\Dashboard::class,
    ],
],

'widgets' => [
    'subject' => 'class',
    'prefix' => 'view',
    'exclude' => [
        \Filament\Widgets\AccountWidget::class,
        \Filament\Widgets\FilamentInfoWidget::class,
    ],
],



namespace App\Filament\Pages;

use ...;
use BezhanSalleh\FilamentShield\Traits\HasPageShield;

class MyPage extends Page
{
    use HasPageShield;
    ...
}



namespace App\Filament\Widgets;

use ...;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;

class IncomeWidget extends LineChartWidget
{
    use HasWidgetShield;
    ...
}

'custom_permissions' => [
    'Impersonate:User' => 'Impersonate User',
    'Export:Order' => 'Export Orders',
],

// Using Select Component
Forms\Components\Select::make('roles')
    ->relationship('roles', 'name')
    ->multiple()
    ->preload()
    ->searchable(),
                    
// Using CheckboxList Component
Forms\Components\CheckboxList::make('roles')
    ->relationship('roles', 'name')
    ->searchable(),

// Using Select Component
Forms\Components\Select::make('roles')
      ->relationship('roles', 'name')
      ->saveRelationshipsUsing(function (Model $record, $state) {
           $record->roles()->syncWithPivotValues($state, [config('permission.column_names.team_foreign_key') => getPermissionsTeamId()]);
      })
     ->multiple()
     ->preload()
     ->searchable(),

// Using CheckboxList Component
Forms\Components\CheckboxList::make('roles')
      ->relationship(name: 'roles', titleAttribute: 'name')
      ->saveRelationshipsUsing(function (Model $record, $state) {
           $record->roles()->syncWithPivotValues($state, [config('permission.column_names.team_foreign_key') => getPermissionsTeamId()]);
      })
     ->searchable(),

FilamentShieldPlugin::make()
    ->navigationLabel('Label')                  // string|Closure|null
    ->navigationIcon('heroicon-o-home')         // string|Closure|null  
    ->activeNavigationIcon('heroicon-s-home')   // string|Closure|null
    ->navigationGroup('Group')                  // string|Closure|null
    ->navigationSort(10)                        // int|Closure|null
    ->navigationBadge('5')                      // string|Closure|null
    ->navigationBadgeColor('success')           // string|array|Closure|null
    ->navigationParentItem('parent.item')       // string|Closure|null
    ->registerNavigation();                     // bool|Closure

FilamentShieldPlugin::make()
    ->modelLabel('Model')                       // string|Closure|null
    ->pluralModelLabel('Models')                // string|Closure|null
    ->recordTitleAttribute('name')              // string|Closure|null
    ->titleCaseModelLabel(false);               // bool|Closure


FilamentShieldPlugin::make()
    ->globallySearchable(true)                  // bool|Closure
    ->globalSearchResultsLimit(50)              // int|Closure
    ->forceGlobalSearchCaseInsensitive(true)    // bool|Closure|null
    ->splitGlobalSearchTerms(false);            // bool|Closure

FilamentShieldPlugin::make()
    ->parentResource(ParentResource::class);    // string|Closure|null

FilamentShieldPlugin::make()
    ->scopeToTenant(true)                       // bool|Closure
    ->tenantRelationshipName('organization')    // string|Closure|null
    ->tenantOwnershipRelationshipName('owner'); // string|Closure|null

   FilamentShieldPlugin::make()
       ->gridColumns([
           'default' => 1,
           'sm' => 2,
           'lg' => 3
       ])
       ->sectionColumnSpan(1)
       ->checkboxListColumns([
           'default' => 1,
           'sm' => 2,
           'lg' => 4,
       ])
       ->resourceCheckboxListColumns([
           'default' => 1,
           'sm' => 2,
       ]),
   

      FilamentShieldPlugin::make()
          ->simpleResourcePermissionView()
    

   FilamentShieldPlugin::make()
       ->localizePermissionLabels()
   

use BezhanSalleh\FilamentShield\Facades\FilamentShield;
use BezhanSalleh\FilamentShield\Commands;
    public function boot(): void
    {
        // individually prohibit commands
        Commands\GenerateCommand::prohibit($this->app->isProduction());
        Commands\InstallCommand::prohibit($this->app->isProduction());
        Commands\PublishCommand::prohibit($this->app->isProduction());
        Commands\SetupCommand::prohibit($this->app->isProduction());
        Commands\SeederCommand::prohibit($this->app->isProduction());
        Commands\SuperAdminCommand::prohibit($this->app->isProduction());
        // or prohibit the above commands all at once
        FilamentShield::prohibitDestructiveCommands($this->app->isProduction());
    }

'localization' => [
     'enabled' => false,
     'key' => 'shield-permissions', // could be any name you want
 ],



/**
 * Shield Permission Labels
 *
 * Translate the values below to localize permission labels in your application.
 */

return [
    // Resource affixes
    'create' => 'Create',
    'delete' => 'Delete',
    'delete_any' => 'Delete Any',
    'force_delete' => 'Force Delete',
    'force_delete_any' => 'Force Delete Any',
    'replicate' => 'Replicate',
    'reorder' => 'Reorder',
    'restore' => 'Restore',
    'restore_any' => 'Restore Any',
    'update' => 'Update',
    'view' => 'View',
    'view_any' => 'View Any',

    // Pages (permission key in snake_case)
    'view_dashboard' => 'Dashboard',

    // Widgets (permission key in snake_case)
    'view_stats_overview' => 'Stats Overview',

    // Custom permissions
    'approve_posts' => 'Approve Posts',
];

            use BezhanSalleh\FilamentShield\Facades\FilamentShield;
            use Filament\Pages\BasePage as Page;
            use Filament\Resources\Resource;
            use Filament\Widgets\Widget;
            use Illuminate\Support\Str;

            //...
            public function boot(): void
            {
                FilamentShield::buildPermissionKeyUsing(
                        function (string $entity, string $affix, string $subject, string $case, string $separator) {
                            return match(true) {
                                # if `configurePermissionIdentifierUsing()` was used previously, then this needs to be adjusted accordingly
                                is_subclass_of($entity, Resource::class) => Str::of($affix)
                                    ->snake()
                                    ->append('_')
                                    ->append(
                                        Str::of($entity)
                                            ->afterLast('\\')
                                            ->beforeLast('Resource')
                                            ->replace('\\', '')
                                            ->snake()
                                            ->replace('_', '::')
                                    )
                                    ->toString(),
                                is_subclass_of($entity, Page::class) => Str::of('page_')
                                    ->append(class_basename($entity))
                                    ->toString(),
                                is_subclass_of($entity, Widget::class) => Str::of('widget_')
                                    ->append(class_basename($entity))
                                    ->toString()
                                };
                        });
            }
            
bash
   php artisan vendor:publish --tag="filament-shield-config"
   
bash
php artisan shield:setup
bash
php artisan shield:translation en --panel=admin
bash
   php artisan vendor:publish --tag="filament-shield-config"
   php artisan shield:publish --panel=admin # you can ignore this if you didn't published the resource previously
   
bash
         php artisan shield:setup --fresh
         
bash
               php artisan shield:generate --resource=FooResource,BarResource --option=policies
               
bash
php artisan vendor:publish --tag="filament-shield-translations"