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 Switch Laravel Package

bezhansalleh/filament-language-switch

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bezhansalleh/filament-language-switch
    

    Publish the config (optional, but recommended for customization):

    php artisan vendor:publish --provider="BezhanSalleh\FilamentLanguageSwitch\FilamentLanguageSwitchServiceProvider"
    
  2. Configure Locales Edit config/filament-language-switch.php and define your supported locales:

    'locales' => [
        'en' => 'English',
        'fr' => 'Français',
        'de' => 'Deutsch',
    ],
    
  3. First Use Case Add the plugin to your Filament panel in Panel.php:

    protected function getPlugins(): array
    {
        return [
            \BezhanSalleh\FilamentLanguageSwitch\FilamentLanguageSwitchPlugin::make(),
        ];
    }
    

    The plugin auto-detects your panel layout (topbar, sidebar, or user menu) and renders the language switcher in the appropriate location.


Implementation Patterns

Core Workflows

  1. Dynamic Locale Detection The plugin automatically detects the current locale from the app() facade or the locale session variable. Override this behavior by binding a custom locale resolver:

    \BezhanSalleh\FilamentLanguageSwitch\FilamentLanguageSwitch::bindLocaleResolver(function () {
        return session('custom_locale_key');
    });
    
  2. Customizing the UI

    • Icon/Label Customization: Pass options to the plugin in Panel.php:
      FilamentLanguageSwitchPlugin::make()
          ->icons([
              'en' => 'heroicon-o-globe-americas',
              'fr' => 'heroicon-o-globe-europe',
          ])
          ->labels([
              'en' => 'English',
              'fr' => 'Français (Custom)',
          ]),
      
    • Position Control: Force a specific position (e.g., sidebar) even if auto-detection fails:
      FilamentLanguageSwitchPlugin::make()->position('sidebar'),
      
  3. Integration with Filament Forms Use the plugin’s LanguageSwitch widget in forms or tables:

    use BezhanSalleh\FilamentLanguageSwitch\Widgets\LanguageSwitch;
    
    LanguageSwitch::make()
        ->label('Select Language')
        ->required(),
    
  4. Middleware for Locale Persistence Combine with Laravel’s SetLocaleMiddleware to persist the selected locale:

    // app/Http/Middleware/SetLocale.php
    public function handle(Request $request, Closure $next)
    {
        if ($request->has('language')) {
            app()->setLocale($request->language);
            session(['locale' => $request->language]);
        }
        return $next($request);
    }
    
  5. Multi-Panel Support Register the plugin separately for each panel with unique configurations:

    // admin/Panel.php
    FilamentLanguageSwitchPlugin::make()->locales(['en', 'es']),
    
    // tenant/Panel.php
    FilamentLanguageSwitchPlugin::make()->locales(['en', 'fr']),
    

Gotchas and Tips

Common Pitfalls

  1. Locale Not Updating

    • Issue: Selected locale doesn’t persist after page reload.
    • Fix: Ensure you’re using Laravel’s SetLocaleMiddleware or manually setting the locale in a middleware/service provider:
      app()->setLocale(session('locale', config('app.locale')));
      
  2. Auto-Detection Fails

    • Issue: Plugin doesn’t render in the expected location (e.g., missing from topbar).
    • Fix: Explicitly set the position or debug your panel’s layout by checking if the plugin is registered in the correct Panel class.
  3. Conflicts with Other Plugins

    • Issue: Language switcher overlaps with other topbar/sidebar items.
    • Fix: Adjust CSS priorities or use the order option:
      FilamentLanguageSwitchPlugin::make()->order(10), // Higher = appears later
      
  4. Missing Translations

    • Issue: Locale labels or icons don’t display correctly.
    • Fix: Ensure your locale keys match those in config/filament-language-switch.php and that the corresponding icons (e.g., Heroicons) are available in your Filament setup.
  5. Caching Issues

    • Issue: Changes to the plugin’s config or UI aren’t reflected.
    • Fix: Clear Filament’s view cache:
      php artisan filament:cache-clear
      

Debugging Tips

  • Log Current Locale: Add this to a middleware or service provider to verify the active locale:
    \Log::info('Current locale:', ['locale' => app()->getLocale()]);
    
  • Inspect Plugin Registration: Check if the plugin is registered in your Panel class by temporarily adding:
    protected function getPlugins(): array {
        \Log::info('Plugins:', array_keys(class_exists(\BezhanSalleh\FilamentLanguageSwitch\FilamentLanguageSwitchPlugin::class)
            ? \BezhanSalleh\FilamentLanguageSwitch\FilamentLanguageSwitchPlugin::make()->getName()
            : []));
        return [...];
    }
    
  • Override Blade Views: Customize the plugin’s views by publishing them:
    php artisan vendor:publish --tag="filament-language-switch-views"
    
    Then modify resources/views/vendor/filament-language-switch/....

Extension Points

  1. Custom Locale Logic Extend the LocaleResolver contract to implement custom logic (e.g., user-preferred language from a database):

    use BezhanSalleh\FilamentLanguageSwitch\Contracts\LocaleResolver;
    
    class DatabaseLocaleResolver implements LocaleResolver {
        public function get(): string {
            return User::find(auth()->id())->preferred_locale ?? config('app.locale');
        }
    }
    

    Bind it in a service provider:

    FilamentLanguageSwitch::bindLocaleResolver(new DatabaseLocaleResolver());
    
  2. Add Flags or Custom Icons Dynamically generate flags or icons based on locale:

    FilamentLanguageSwitchPlugin::make()
        ->icons(function (string $locale) {
            return match ($locale) {
                'en' => 'heroicon-o-globe-americas',
                'fr' => 'flag-fr', // Use a custom icon class
                default => 'heroicon-o-globe-europe',
            };
        }),
    
  3. Conditional Rendering Hide the language switcher for specific users or roles:

    FilamentLanguageSwitchPlugin::make()
        ->visible(fn () => auth()->user()->can('switch-languages')),
    
  4. API Integration Expose the current locale via an API endpoint:

    Route::get('/api/locale', function () {
        return response()->json(['locale' => app()->getLocale()]);
    });
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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