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 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 (or your configured path). Here, you can:

    • Create API tokens for users.
    • Revoke existing tokens.
    • View token details (e.g., abilities, expiration).

Implementation Patterns

Core Workflows

  1. Token Management

    • Create Tokens: Use the built-in UI to generate tokens for users. The package handles token creation via Sanctum’s createToken() method under the hood.
      // Example: Programmatically create a token (optional)
      $user = User::find(1);
      $token = $user->createToken('API Token Name');
      
    • Bulk Actions: Revoke multiple tokens at once using the table’s bulk action dropdown.
  2. Integration with Filament Resources

    • Filtering by Token: Extend a Filament resource to filter records based on the authenticated Sanctum token’s abilities:
      public static function getTableRecordsQuery(Table $table): QueryBuilder
      {
          $user = $table->getUser();
          return parent::getTableRecordsQuery($table)
              ->where('user_id', $user->id)
              ->when($user->cannot('view-all-tokens'), fn($q) => $q->where('user_id', $user->id));
      }
      
  3. Customizing Token Creation

    • Override the default token creation logic by extending the plugin’s CreateTokenAction:
      use Devtical\FilamentSanctum\Actions\CreateTokenAction;
      
      class CustomCreateTokenAction extends CreateTokenAction
      {
          protected function handle(): void
          {
              $token = $this->user->createToken($this->name, $this->abilities);
              // Custom logic (e.g., log token creation, send email)
              $this->redirect('/admin/sanctum-tokens');
          }
      }
      
    • Register the custom action in the plugin’s configuration:
      'create_token_action' => \App\Actions\CustomCreateTokenAction::class,
      
  4. API Token Authentication in Filament

    • Use Sanctum tokens to authenticate API requests to Filament’s API endpoints. Example in a controller:
      use Illuminate\Http\Request;
      use Illuminate\Support\Facades\Gate;
      
      public function store(Request $request)
      {
          $request->user(); // Authenticated via Sanctum token
          Gate::authorize('create', Model::class);
          // Proceed with logic
      }
      
  5. Localization and Translations

    • Customize translations by publishing the language files and overriding them in resources/lang/vendor/filament-sanctum/.

Gotchas and Tips

Pitfalls

  1. Token Abilities vs. Filament Permissions

    • Sanctum token abilities ($token->abilities) are not the same as Filament’s gate policies. Ensure you align them in your AuthServiceProvider:
      Gate::define('view-all-tokens', function ($user) {
          return $user->hasRole('admin'); // Example: Use a role-based check
      });
      
  2. Token Expiration Handling

    • By default, Sanctum tokens do not expire. Configure expiration in config/sanctum.php:
      'expiration' => now()->addDays(15),
      
    • The package does not auto-revoke expired tokens; implement a scheduled job to clean them up:
      // app/Console/Commands/RevokeExpiredTokens.php
      use Illuminate\Support\Facades\DB;
      
      public function handle()
      {
          DB::table('personal_access_tokens')
              ->where('last_used_at', '<=', now()->subDays(15))
              ->delete();
      }
      
  3. CSRF and Sanctum Conflicts

    • If using Sanctum for API auth, ensure your Filament admin panel uses the correct middleware. Add this to app/Http/Kernel.php:
      'web' => [
          \App\Http\Middleware\EncryptCookies::class,
          \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
          \Illuminate\Session\Middleware\StartSession::class,
          // Sanctum middleware for API routes (if needed)
          \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
          \Illuminate\View\Middleware\ShareErrorsFromSession::class,
          \App\Http\Middleware\VerifyCsrfToken::class,
          \Illuminate\Routing\Middleware\SubstituteBindings::class,
      ],
      
  4. Performance with Large Token Tables

    • The package loads all tokens for the current user by default. For users with many tokens, optimize with pagination or lazy loading:
      // In a custom resource table
      public static function getTableRecordsQuery(Table $table): QueryBuilder
      {
          return parent::getTableRecordsQuery($table)
              ->latest()
              ->paginate(20); // Limit results
      }
      

Debugging Tips

  1. Token Not Showing in UI?

    • Verify the user has at least one token:
      php artisan tinker
      >>> $user = App\Models\User::find(1);
      >>> $user->tokens
      
    • Check Sanctum’s personal_access_tokens table for orphaned records.
  2. Permission Denied Errors

    • Ensure the Sanctum token’s abilities match the Filament policy requirements. Test with:
      php artisan sanctum:inspect
      
  3. Plugin Not Loading

    • Clear Filament’s cache:
      php artisan filament:cache-reset
      
    • Verify the plugin is registered in AdminPanelProvider.

Extension Points

  1. Custom Token Fields

    • Extend the token table columns by publishing the views and modifying resources/views/filament-sanctum/...:
      <!-- Example: Add a custom column -->
      <td>
          {{ $record->last_used_at->diffForHumans() }}
      </td>
      
  2. Webhook on Token Creation

    • Listen to the sanctum.token-created event in EventServiceProvider:
      protected $listen = [
          \Devtical\FilamentSanctum\Events\TokenCreated::class => [
              \App\Listeners\LogTokenCreation::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);
      }
      
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony