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

Laravel Google Fonts Laravel Package

spatie/laravel-google-fonts

Self-host Google Fonts in Laravel with minimal setup. Register Google Fonts CSS URLs in config and load them via the @googlefonts Blade directive. On first request it downloads CSS/assets, caches locally, inlines CSS, and falls back to Google if needed.

View on GitHub
Deep Wiki
Context7
## Getting Started

1. **Installation**:
   ```bash
   composer require spatie/laravel-google-fonts
   php artisan vendor:publish --provider="Spatie\GoogleFonts\GoogleFontsServiceProvider" --tag="google-fonts-config"
  • Publish the config file to customize settings (e.g., config/google-fonts.php).
  1. Register Fonts: Add Google Fonts embed URLs to the fonts array in the config:

    'fonts' => [
        'default' => 'https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap',
        'secondary' => 'https://fonts.googleapis.com/css2?family=Roboto:wght@300;400&display=swap',
    ],
    
  2. First Use Case: Load fonts in Blade views using the @googlefonts directive:

    <head>
        @googlefonts  <!-- Loads 'default' font -->
        @googlefonts('secondary')  <!-- Loads 'secondary' font -->
    </head>
    
  3. Prefetch Fonts (Optional): Run the Artisan command to pre-download fonts for immediate availability:

    php artisan google-fonts:fetch
    

Implementation Patterns

1. Font Management Workflow

  • Centralized Configuration: Define all fonts in config/google-fonts.php for consistency.
  • Dynamic Loading: Use named fonts in Blade directives (e.g., @googlefonts('code')) to avoid hardcoding URLs.
  • Fallback Handling: Configure fallback to false in debug mode to enforce local hosting (throws exceptions if fonts fail to load).

2. Performance Optimization

  • Inline CSS: Enable inline: true (default) to reduce HTTP requests.
  • Preload Fonts: Set preload: true to prioritize font loading via <link rel="preload">.
  • Lazy Fetching: Use the --lazy flag with google-fonts:fetch to skip already downloaded fonts:
    php artisan google-fonts:fetch --lazy
    

3. Integration with CSP

  • Pass a nonce to the directive for Content Security Policy compliance:
    @googlefonts(['nonce' => csp_nonce()])
    

4. Storage and Deployment

  • Local Storage: Fonts are stored in storage/app/public/fonts (default). Run php artisan storage:link to make them publicly accessible.
  • CDN Support: Configure a custom disk (e.g., disk: 's3') in the config to offload fonts to a CDN.
  • Git Ignore: Exclude storage/app/public/fonts from .gitignore if fonts should be version-controlled.

5. Legacy Browser Support

  • Override the user_agent in config to target older browsers (e.g., IE) if needed:
    'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
    

Gotchas and Tips

Pitfalls

  1. Storage Link Requirement:

    • Forgetting php artisan storage:link will break font loading (404 errors).
    • Fix: Add php artisan storage:link to your deployment script.
  2. Debug Mode Fallback:

    • In debug mode (APP_DEBUG=true), the package falls back to Google’s CDN if local fonts fail to load.
    • Tip: Set 'fallback' => false in debug mode to catch issues early:
      'fallback' => env('APP_DEBUG') ? false : true,
      
  3. Font URL Parsing:

    • URLs without .woff2 extensions (e.g., family=Roboto:wght@400) may cause parsing errors.
    • Fix: Ensure URLs include explicit file extensions (e.g., &display=swap is required).
  4. Preload Tag Issues:

    • Preload tags in older versions referenced Google’s URLs instead of local files.
    • Fix: Update to v1.4.4+ where preload tags correctly point to local assets.
  5. Caching Headers:

    • Self-hosted fonts may not respect Cache-Control headers if stored in public disk.
    • Tip: Use a CDN or configure storage/app/public with proper caching rules.

Debugging Tips

  • Check Font Downloads: Verify fonts exist in storage/app/public/fonts after running google-fonts:fetch.
    ls storage/app/public/fonts
    
  • Inspect Blade Output: Use @googlefonts(['debug' => true]) (if supported) or check rendered HTML for errors.
  • Log Failures: Enable Laravel’s debug mode and check logs for Spatie\GoogleFonts exceptions.

Extension Points

  1. Custom Fetch Logic: Override the Spatie\GoogleFonts\Fetchers\FontFetcher class to implement custom download logic (e.g., proxy requests).

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->bind(
            \Spatie\GoogleFonts\Fetchers\FontFetcher::class,
            \App\CustomFontFetcher::class
        );
    }
    
  2. Dynamic Font Registration: Register fonts programmatically via the GoogleFonts facade:

    use Spatie\GoogleFonts\Facades\GoogleFonts;
    
    GoogleFonts::addFont('dynamic-font', 'https://fonts.googleapis.com/...');
    
  3. Event Listeners: Listen for font fetch events to log or process downloads:

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        \Spatie\GoogleFonts\Events\FontsFetched::class => [
            \App\Listeners\LogFontDownload::class,
        ],
    ];
    

Pro Tips

  • Bulk Fetching: Use --lazy with google-fonts:fetch in CI/CD to avoid redundant downloads.
  • Font Subsetting: Manually subset fonts before self-hosting to reduce file size (use Google Fonts Subset Tool).
  • Monitor Updates: Re-run google-fonts:fetch periodically to update fonts if Google releases new versions.
  • Local Development: Disable fallback in .env for local testing:
    GOOGLE_FONTS_FALLBACK=false
    

---
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
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