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

Spatie Laravel Google Fonts Plugin Laravel Package

filament/spatie-laravel-google-fonts-plugin

Adds a Spatie Google Fonts provider to Filament panels, letting you use locally fetched and cached Google Fonts via spatie/laravel-google-fonts. Configure with Panel::font('Inter', provider: SpatieGoogleFontProvider::class) to avoid CDNs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies Run:

    composer require spatie/laravel-google-fonts:"^4.0" filament/spatie-laravel-google-fonts-plugin:"^5.0" -W
    

    Follow Spatie’s setup guide to configure the base package (e.g., .env settings, caching).

  2. Register the Plugin In your Panel configuration (e.g., app/Providers/Filament/AdminPanelProvider.php), add:

    use Filament\FontProviders\SpatieGoogleFontProvider;
    
    public function panel(Panel $panel): Panel {
        return $panel
            ->font('Inter', provider: SpatieGoogleFontProvider::class);
    }
    

    Replace 'Inter' with your desired Google Font (must be pre-configured in Spatie’s package).

  3. Verify Setup Clear caches and restart your dev server:

    php artisan optimize:clear
    php artisan cache:clear
    

    Check the Filament panel—your font should now render locally (no CDN calls).


First Use Case

Replace CDN-based fonts with self-hosted alternatives in Filament’s admin panel. Example: Replace default Roboto with Inter (or Poppins, Roboto Mono, etc.) for a modern look without external requests.


Implementation Patterns

Core Workflows

  1. Font Selection & Registration

    • Dynamic Font Switching: Use a config file or database to toggle fonts per panel/tenant:

      // app/Config/filament.php
      'fonts' => [
        'default' => 'Inter',
        'fallback' => 'Roboto',
      ],
      

      Then reference in panel():

      ->font(config('filament.fonts.default'), provider: SpatieGoogleFontProvider::class)
      
    • Multi-Panel Support: Extend SpatieGoogleFontProvider to support panel-specific font sets:

      class CustomFontProvider extends SpatieGoogleFontProvider {
          public function getFont(): string {
              return request()->routeIs('admin*') ? 'Inter' : 'Lato';
          }
      }
      
  2. Integration with Filament Themes

    • Pair with Filament’s theme system to apply fonts conditionally:
      ->theme(Theme::make('dark')
          ->font('Inter', provider: SpatieGoogleFontProvider::class)
      )
      
  3. Asset Optimization

    • Preload Critical Fonts: Add to app/Providers/AppServiceProvider.php:
      public function boot() {
          if (app()->environment('production')) {
              FontManager::preload('Inter');
          }
      }
      
    • Cache Invalidation: Trigger font updates after adding new fonts to Spatie’s config:
      php artisan google-fonts:clear-cache
      

Advanced Patterns

  1. Custom Font Families Extend Spatie’s config to include custom subsets/variants:

    // config/google-fonts.php
    'fonts' => [
        'Inter' => [
            'weights' => ['100', '400', '700'],
            'styles' => ['italic'],
        ],
    ],
    

    Then use in Filament:

    ->font('Inter', weights: ['400', '700'], styles: ['italic'])
    
  2. Fallback Chains Define fallback fonts in Spatie’s config and pass them to Filament:

    // config/google-fonts.php
    'fallbacks' => [
        'Inter' => ['Roboto', 'Arial'],
    ],
    

    Filament will automatically handle the chain via the provider.

  3. Dynamic Font Loading Lazy-load fonts for non-critical pages using Filament’s resource hooks:

    use Filament\Resources\Resource;
    
    public function getPages(): array {
        return [
            Resource::make(Page::class)
                ->pages([
                    ListPages::make()
                        ->font('Inter', provider: SpatieGoogleFontProvider::class),
                ]),
        ];
    }
    

Gotchas and Tips

Pitfalls

  1. Font Not Loading?

    • Issue: Font files missing or cached.
    • Fix:
      • Run php artisan google-fonts:download to ensure files exist in storage/app/google-fonts.
      • Clear Filament’s view cache: php artisan view:clear.
      • Verify the font name matches Spatie’s config exactly (case-sensitive).
  2. Mixed CDN/Local Sources

    • Issue: Filament may still load fonts from CDN if the @googlefonts directive isn’t processed.
    • Fix: Ensure Spatie’s package is properly booting before Filament initializes. Add this to AppServiceProvider:
      public function boot() {
          $this->loadGoogleFonts();
      }
      
  3. Performance Overhead

    • Issue: Large font families (e.g., Roboto with 10+ weights) bloat asset size.
    • Fix: Limit weights/styles in Spatie’s config and Filament’s provider:
      ->font('Inter', weights: ['400', '500'], styles: [])
      
  4. Panel-Specific Conflicts

    • Issue: Fonts not applying to all panels (e.g., filament/admin vs. filament/tenant).
    • Fix: Scope the provider in each panel’s config or use a panel service provider.

Debugging Tips

  1. Check Downloaded Fonts Inspect storage/app/google-fonts for missing files. Run:

    php artisan google-fonts:download --font=Inter
    
  2. Verify Blade Directives Ensure @googlefonts directives render in Filament’s views. Add this to a test blade file:

    @googlefonts(['Inter'])
    

    If missing, Spatie’s package isn’t booting early enough.

  3. Log Provider Calls Temporarily add logging to SpatieGoogleFontProvider to debug font resolution:

    public function getFontUrl(): string {
        \Log::debug('Resolving font URL for:', $this->font);
        return parent::getFontUrl();
    }
    

Extension Points

  1. Custom Provider Logic Extend SpatieGoogleFontProvider to add logic like:

    • User-Based Fonts: Fetch fonts from a user’s profile.
      class UserFontProvider extends SpatieGoogleFontProvider {
          public function getFont(): string {
              return auth()->user()->preferred_font ?? 'Inter';
          }
      }
      
    • A/B Testing: Randomly assign fonts to test performance/UX.
  2. Hybrid CDN/Local Fallback Modify the provider to fall back to CDN if local files are missing:

    public function getFontUrl(): string {
        $localUrl = parent::getFontUrl();
        return file_exists(public_path($localUrl)) ? $localUrl : "https://fonts.googleapis.com/...";
    }
    
  3. Font Analytics Track font usage with a middleware or observer:

    // app/Providers/FontObserverServiceProvider.php
    public function boot() {
        FontManager::resolving(function ($font) {
            \Log::info("Font resolved: {$font->getFontName()}");
        });
    }
    

Config Quirks

  1. Caching Behavior

    • Spatie’s package caches fonts for 24 hours by default. Override in .env:
      GOOGLE_FONTS_CACHE_TTL=minutes
      
    • Filament’s view cache may need clearing after changes.
  2. Font Name Validation

    • Spatie’s config validates font names against Google’s API. Use this list to avoid errors.
  3. Storage Permissions Ensure storage/app/google-fonts is writable:

    chmod -R 755 storage/app/google-fonts
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui