PHP code example of happenv-com / filament-access-control

1. Go to this page and download the library: Download happenv-com/filament-access-control 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/ */

    

happenv-com / filament-access-control example snippets


use Happenv\FilamentAccessControl\FilamentAccessControlPlugin;
use Happenv\FilamentAccessControl\Schemas\Components\PermissionEditor;

$panel->plugin(
    FilamentAccessControlPlugin::make()
        ->roleModel(Role::class)
        ->superAdminRole('administrator'),
);

// In the role's (or the user's) form:
PermissionEditor::make()->deferred();

use Happenv\FilamentAccessControl\Contracts\HasEditablePermissions;
use Happenv\LaravelAccessControl\Contracts\AuthControllable;
use Happenv\LaravelAccessControl\Traits\HasPermissions;
use Illuminate\Support\Collection;

class Role extends Model implements AuthControllable, HasEditablePermissions
{
    use HasPermissions;

    protected $casts = ['permissions' => 'array'];

    public function getPermissions(): Collection
    {
        return collect($this->permissions ?? [])->filter(fn ($slug) => is_string($slug))->values();
    }

    public function setPermissions(Collection $permissions): void
    {
        $this->permissions = $permissions->values()->all();
        $this->save();
    }
}

use Happenv\FilamentAccessControl\FilamentAccessControlPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        ->plugin(
            FilamentAccessControlPlugin::make()
                ->roleModel(Role::class)
                ->superAdminRole('administrator') // the `code` of the role that holds everything
                ->roleAbilities(
                    viewAny: RolePermission::View,
                    create: RolePermission::Create,
                    update: RolePermission::Update,
                ),
        );
}

FilamentAccessControlPlugin::make()
    ->roleModel(Role::class)
    ->roleTitleAttribute('name')                          // or fn (Role $role): string
    ->modifyRolesQueryUsing(fn (Builder $query) => $query->orderBy('name'))
    ->superAdminRole(fn (Role $role): bool => $role->is_admin)
    ->rolesShownByDefault(8)                               // see "Many roles" below
    ->modifyCreateRoleActionUsing(fn (CreateAction $action) => $action->schema([
        TextInput::make('name')->

FilamentAccessControlPlugin::make()
    ->rolesShownByDefault(8)     // the first eight roles, in the roles query's order, until the operator picks others
    ->deferRolePicker(false);    // apply every tick at once instead of on Apply

PermissionMatrix::make()->rolesShownByDefault(8)->deferRolePicker(false);   // or per component

use Happenv\FilamentAccessControl\Schemas\Components\PermissionMatrix;

PermissionMatrix::make()->deferred();

use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Happenv\FilamentAccessControl\Schemas\Components\PermissionEditor;

public static function configure(Schema $schema): Schema
{
    return $schema->components([
        Tabs::make()->tabs([
            Tab::make('Role')->schema([
                TextInput::make('name')->

PermissionEditor::make()->disabled()->showDirectGrants(false);

FilamentAccessControlPlugin::make()->deferred();   // the default for every screen of the plugin

PermissionEditor::make()->deferred();               // or per component
PermissionEditor::make()->deferred(false);

FilamentAccessControlPlugin::make()->counters();   // every screen of the plugin

PermissionEditor::make()->counters();              // or per component
PermissionMatrix::make()->counters(false);

PermissionEditor::make()->ability(fn (User $record): string => $record->is_api_key ? 'manageApiKey' : 'update');

// Instead of what the operator holds in effect — slugs or permission enums; null for anything:
FilamentAccessControlPlugin::make()
    ->grantableBy(fn (User $operator): ?array => $operator->is_support ? [OrderPermission::Refund] : null);

// Or switch the guard off:
FilamentAccessControlPlugin::make()->preventEscalation(false);

FilamentAccessControlPlugin::make()->preventSelfEditing(false);

PermissionEditor::make()->surface(PermissionSurface::Api);

use Happenv\FilamentAccessControl\Attributes\RequiresMFA;
use Happenv\LaravelAccessControl\Contracts\PermissionDefinition;

enum OrderPermission: string implements PermissionDefinition
{
    #[RequiresMFA]
    case Refund = 'order.refund';

    // The providers of a named panel, rather than the current one:
    #[RequiresMFA(panel: 'admin')]
    case Export = 'order.export';
}

use Happenv\FilamentAccessControl\Forms\Components\PermissionSelector;

PermissionSelector::make('permissions')->surface(PermissionSurface::Api);

use Happenv\FilamentAccessControl\Support\PermissionTree;

PermissionTree::resolveActionLabelsUsing(
    fn (PermissionDto $permission): ?string => __("app.permission-verbs.{$permission->enum->name}"),
);

class ScopedPermissionWriter extends PermissionWriter
{
    protected function ensureMayWrite(Model $locked, Collection $resulting, Collection $granted, Collection $revoked): void
    {
        if ($granted->contains(OrderPermission::View->value) && ! $locked->channels()->exists()) {
            throw new PermissionWriteRefused(__('app.roles.choose_channels_first'));
        }
    }
}

$this->app->bind(PermissionWriter::class, ScopedPermissionWriter::class);

use Filament\Actions\Action;
use Filament\Forms\Components\CheckboxList;
use Happenv\FilamentAccessControl\Support\CellNote;

FilamentAccessControlPlugin::make()
    ->holderCellNotes(fn (Model $holder, PermissionDto $permission): ?CellNote => match (true) {
        $permission->enum !== OrderPermission::View => null,
        $holder->channels->isEmpty() => new CellNote(__('app.scope.none'), color: 'warning', action: 'channelScope'),
        default => new CellNote(trans_choice('app.scope.channels', $holder->channels->count()), tooltip: $holder->channels->pluck('name')->join(', '), action: 'channelScope'),
    })
    // A closure, evaluated per request: labels translate in the request's locale.
    ->actions(fn (): array => [
        Action::make('channelScope')
            ->slideOver()
            ->authorize(fn (array $arguments): bool => Gate::allows('update', Role::find($arguments['holder'])))
            ->fillForm(fn (array $arguments): array => ['channels' => Role::find($arguments['holder'])->channels->modelKeys()])
            ->schema([CheckboxList::make('channels')->options(Channel::pluck('name', 'id'))])
            ->action(fn (array $arguments, array $data) => Role::find($arguments['holder'])->channels()->sync($data['channels'])),
    ]);
bash
php artisan vendor:publish --tag="filament-access-control-views"
php artisan vendor:publish --tag="filament-access-control-translations"
bash
php artisan vendor:publish --tag="filament-access-control-translations"