Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Filament Sanctum Laravel Package

devtical/filament-sanctum

Filament Sanctum adds a Filament panel for managing Laravel Sanctum API tokens. Create and view personal access tokens from the admin UI, with publishable config and translations for easy customization.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require devtical/filament-sanctum
    php artisan vendor:publish --tag=filament-sanctum-config
    php artisan vendor:publish --tag=filament-sanctum-translations
    

    Publish the config and translations to customize behavior, expiration defaults, and language.

  2. Register the Plugin Add the plugin to your Filament admin panel in app/Providers/Filament/AdminPanelProvider.php:

    public function panel(Panel $panel): Panel
    {
        return $panel
            ->plugins([
                \Devtical\FilamentSanctum\FilamentSanctumPlugin::make(),
            ]);
    }
    
  3. First Use Case Access the Sanctum token management UI at /admin/sanctum-tokens (configurable via sanctum_url in config). Key features:

    • Create tokens with preset expiration (7/30/60/90 days) or custom dates.
    • Revoke tokens via bulk actions or per-row buttons.
    • View details in a modal (abilities, expiration, timestamps).
    • Restricted access via Laravel gates (configured in authorization config).

Implementation Patterns

Core Workflows

  1. Token Management with Expiration

    • Create Tokens with Expiration: The UI now includes expiration presets. Programmatically:
      // Custom expiration (e.g., 15 days)
      $token = $user->createToken('API Token', [], now()->addDays(15));
      
      // Use preset (e.g., 30 days)
      $token = $user->createToken('API Token', [], now()->addDays(config('filament-sanctum.default_expiration_days')));
      
    • Bulk Revoke: Use the table’s bulk action dropdown or revoke individually via per-row buttons.
  2. Integration with Filament 5

    • Resource Filtering:
      public static function getTableRecordsQuery(Table $table): QueryBuilder
      {
          return parent::getTableRecordsQuery($table)
              ->when(
                  $table->getUser()->cannot('view-all-tokens'),
                  fn($q) => $q->where('user_id', $table->getUser()->id)
              );
      }
      
    • Customize Navigation: Update the config to change the URL slug:
      'sanctum_url' => 'api-tokens', // Changes path to `/admin/api-tokens`
      
  3. Customizing Token Creation

    • Extend the CreateTokenAction to add logic (e.g., logging, notifications):
      use Devtical\FilamentSanctum\Actions\CreateTokenAction;
      
      class CustomCreateTokenAction extends CreateTokenAction
      {
          protected function handle(): void
          {
              $expiration = $this->expiration ?? now()->addDays(config('filament-sanctum.default_expiration_days'));
              $token = $this->user->createToken($this->name, $this->abilities, $expiration);
              // Custom logic (e.g., send email)
              $this->dispatch(new TokenCreated($token));
          }
      }
      
    • Register the custom action in config/filament-sanctum.php:
      'create_token_action' => \App\Actions\CustomCreateTokenAction::class,
      
  4. Authorization

    • Restrict access to the Sanctum page via a Laravel gate:
      // config/filament-sanctum.php
      'authorization' => 'view-sanctum-tokens',
      
      Define the gate in AuthServiceProvider:
      Gate::define('view-sanctum-tokens', function ($user) {
          return $user->hasRole(['admin', 'api-manager']);
      });
      
  5. Localization

    • Override translations for expiration labels or token details:
      // resources/lang/vendor/filament-sanctum/en/messages.php
      return [
          'expiration' => 'Valid Until',
          'never_expires' => 'Never Expires',
      ];
      

Gotchas and Tips

Pitfalls

  1. URL Resolution Issues

    • Fixed in v1.1.0: Duplicate /admin/admin/sanctum paths are resolved via Sanctum::getUrl().
    • Debugging: Verify the sanctum_url config key and clear Filament’s cache:
      php artisan filament:cache-reset
      
  2. Token Abilities Display

    • Fixed in v1.1.0: Repeated "None" text for abilities is resolved. Ensure your abilities column uses TextColumn (not TagsColumn):
      TextColumn::make('abilities')
          ->formatStateUsing(fn($state) => implode(', ', $state)),
      
  3. Expiration Handling

    • No Auto-Revoke: Tokens expire at the set time but aren’t auto-revoked. Schedule a job:
      // app/Console/Commands/RevokeExpiredTokens.php
      public function handle()
      {
          DB::table('personal_access_tokens')
              ->where('expires_at', '<=', now())
              ->delete();
      }
      
    • Config Defaults: Set default_expiration_days in config/filament-sanctum.php:
      'default_expiration_days' => 30,
      
  4. Filament 5 Migration

    • Breaking Change: MenuItem is replaced with Action. Update custom plugins:
      // Old (v1.0.x)
      MenuItem::make('Sanctum Tokens', 'heroicon-o-key')
      
      // New (v1.1.0)
      Action::make('sanctum-tokens')
          ->icon('heroicon-o-key')
          ->url(fn() => Sanctum::getUrl());
      

Debugging Tips

  1. Token Not Showing?

    • Check the personal_access_tokens table for orphaned records:
      php artisan tinker
      >>> \Devtical\FilamentSanctum\Facades\Sanctum::getTokensForUser(auth()->user());
      
    • Verify the user has the view-sanctum-tokens gate.
  2. Permission Denied

    • Test gate access:
      php artisan gate:test view-sanctum-tokens
      
    • Ensure the gate is defined in AuthServiceProvider.
  3. Plugin Not Loading

    • Clear Filament’s cache and check for config errors:
      php artisan filament:cache-reset
      php artisan config:clear
      

Extension Points

  1. Custom Token Fields

    • Extend the token table by publishing views:
      php artisan vendor:publish --tag=filament-sanctum-views
      
    • Add columns to resources/views/filament-sanctum/columns/...:
      <x-filament-tables::td>
          {{ $getRecord()->expires_at?->diffForHumans() ?? __('filament-sanctum::messages.never_expires') }}
      </x-filament-tables::td>
      
  2. Token Events

    • Listen for token creation/revocation:
      // app/Providers/EventServiceProvider.php
      protected $listen = [
          \Devtical\FilamentSanctum\Events\TokenCreated::class => [
              \App\Listeners\LogTokenEvent::class,
          ],
          \Devtical\FilamentSanctum\Events\TokenRevoked::class => [
              \App\Listeners\NotifyTokenRevocation::class,
          ],
      ];
      
  3. Multi-Tenant Support

    • Filter tokens by tenant in the resource query:
      public static function getTableRecordsQuery(Table $table): QueryBuilder
      {
          return parent::getTableRecordsQuery($table)
              ->where('tokens.tenant_id', tenant()->id);
      }
      
  4. Expiration Presets

    • Customize presets in config/filament-sanctum.php:
      'expiration_presets' => [
          '7_days' => __('filament-sanctum::messages.days_7'),
          '30_days' => __('filament-sanctum::messages.days_30'),
          'custom' => __('filament-sanctum::messages.custom_date'),
      ],
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky