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 Language Switcher Laravel Package

craft-forge/filament-language-switcher

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require craft-forge/filament-language-switcher
    

    Ensure your composer.json meets the package's PHP 8.1+ and Filament 3.x/4.x/5.x requirements.

  2. Register the Plugin: Add the plugin to your AdminPanelProvider (or other panel provider):

    use CraftForge\FilamentLanguageSwitcher\FilamentLanguageSwitcherPlugin;
    
    public function panel(Panel $panel): Panel {
        return $panel->plugins([
            FilamentLanguageSwitcherPlugin::make(),
        ]);
    }
    
  3. First Use Case:

    • The plugin auto-detects available Filament translations (e.g., resources/lang/) and renders a dropdown with flags in the Filament navbar.
    • Test by accessing your Filament admin panel—no additional configuration is needed for basic functionality.

Implementation Patterns

Core Workflows

  1. Auto-Detection:

    • The plugin scans resources/lang/ for .json files (e.g., en.json, fr.json) and maps them to locales.
    • Override auto-detection by explicitly defining locales in the plugin config:
      FilamentLanguageSwitcherPlugin::make()
          ->locales(['en', 'fr', 'de'])
      
  2. Customization:

    • Flags: Use flags() to map locales to custom flag icons (e.g., ['en' => '🇬🇧']).
    • Labels: Override default locale names with labels():
      ->labels(['en' => 'English', 'fr' => 'Français'])
      
    • Position: Control dropdown placement via position() (e.g., 'end' for navbar right side).
  3. Persistence:

    • Session-based: Default behavior persists locale via PHP sessions.
    • Cookie-based: Enable with persistViaCookies(true) (requires session() config in config/filament.php).
  4. Integration with Filament Features:

    • Auth Pages: Works out-of-the-box with Filament’s login/register pages.
    • Events: Listen to LocaleChanged events for post-switch logic:
      event(new FilamentLanguageSwitcher\Events\LocaleChanged($newLocale));
      
  5. Multi-Panel Support:

    • Register the plugin in each panel provider where language switching is needed.

Advanced Patterns

  1. Dynamic Locale Loading:

    • Fetch locales from a database or API:
      ->locales(fn () => Locale::query()->pluck('code')->toArray())
      
  2. Conditional Rendering:

    • Hide the switcher for specific users/roles:
      ->visible(fn () => auth()->user()->isAdmin())
      
  3. Localization Fallbacks:

    • Combine with spatie/laravel-translatable for fallback chains:
      ->fallbackLocale('en')
      
  4. Testing:

    • Mock the plugin in tests:
      $this->partialMock(FilamentLanguageSwitcherPlugin::class, function ($mock) {
          $mock->shouldReceive('getLocales')->andReturn(['en', 'es']);
      });
      

Gotchas and Tips

Pitfalls

  1. Locale File Naming:

    • The plugin expects snake_case filenames (e.g., en_US.jsonen_us.json). Rename files if auto-detection fails.
  2. Caching Issues:

    • Clear Filament’s view cache (php artisan filament:cache-clear) after adding new locales or flags.
  3. Session/Cookie Conflicts:

    • If using persistViaCookies(true), ensure session() is configured in config/filament.php:
      'session' => [
          'driver' => 'database', // or 'cookie', 'redis', etc.
      ],
      
  4. Dark Mode Flags:

    • Flags may appear faint in dark mode. Use solid emoji (e.g., 🇫🇷 instead of 🇫🇷) or SVG icons for better contrast.
  5. Locale Code Mismatches:

    • Ensure locale codes in locales() match those in your translation files (e.g., en_US vs. en).

Debugging Tips

  1. Log Auto-Detected Locales: Add this to your AppServiceProvider to debug:

    public function boot() {
        \Log::info('Detected locales:', [
            'locales' => app(FilamentLanguageSwitcherPlugin::class)->getLocales(),
        ]);
    }
    
  2. Check Event Firing: Listen for LocaleChanged events to verify triggers:

    event(new \CraftForge\FilamentLanguageSwitcher\Events\LocaleChanged($locale));
    
  3. Override Blade Views: Customize the dropdown template by publishing views:

    php artisan vendor:publish --tag="filament-language-switcher-views"
    

    Then modify resources/views/vendor/filament-language-switcher/....


Extension Points

  1. Custom Storage: Extend persistence logic by binding a custom locale resolver:

    $this->app->bind(\CraftForge\FilamentLanguageSwitcher\Contracts\LocaleResolver::class, function () {
        return new CustomResolver();
    });
    
  2. API Integration: Sync locales with a headless CMS (e.g., Strapi) via a scheduled job:

    public function handle() {
        $locales = $this->fetchLocalesFromStrapi();
        app(FilamentLanguageSwitcherPlugin::class)->locales($locales);
    }
    
  3. Localization Providers: Integrate with laravel-localization or mcamara/laravel-localization for advanced features like:

    • Right-to-left (RTL) support.
    • Locale-specific URLs (e.g., /en/page).
  4. Testing Helpers: Create a trait for testing locale switches:

    trait TestsLocaleSwitching {
        protected function switchLocale(string $locale) {
            $this->actingAsUser(factory(User::class)->create());
            $this->post('/filament-language-switcher/change', ['locale' => $locale]);
        }
    }
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
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