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

aristonis/laravel-language-switcher

Auto-detect and switch your Laravel app locale using browser headers, session, or custom detectors. Includes middleware for per-request locale setting, session persistence, optional user profile integration, and a Blade component plus controller route for manual language selection.

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package via Composer:

composer require aristonis/laravel-language-switcher

Publish the configuration and migration files:

php artisan vendor:publish --provider="Aristonis\LanguageSwitcher\LanguageSwitcherServiceProvider"

Run the migrations to create the necessary tables:

php artisan migrate

Register the middleware in app/Http/Kernel.php:

protected $middlewareGroups = [
    'web' => [
        // ...
        \Aristonis\LanguageSwitcher\Middleware\LanguageSwitcher::class,
    ],
];

Add the language switcher blade directive in your layout file:

@languageSwitcher

First Use Case: Display a language switcher dropdown in your navigation bar. The package automatically detects the user's preferred language (via browser or session) and applies it to the current request.


Implementation Patterns

Basic Usage

  1. Language Detection: The package detects language preference in this order: session > cookie > browser > default. Override the default language in config/language-switcher.php:

    'default' => 'en',
    'supported' => ['en', 'es', 'fr'],
    
  2. Manual Language Switching: Use the facade to switch languages programmatically:

    use Aristonis\LanguageSwitcher\Facades\LanguageSwitcher;
    
    LanguageSwitcher::set('es'); // Force Spanish
    
  3. Route-Based Language Switching: Prefix routes with language codes (e.g., /en/about, /es/about). Configure in config/language-switcher.php:

    'prefix' => true,
    
  4. Blade Directives:

    • @languageSwitcher: Renders the default dropdown.
    • @languageSwitcher(['es', 'fr']): Customize supported languages for a specific view.
    • @language: Displays the current language name (e.g., "English").
  5. Localization: Use Laravel's built-in localization with language-specific files (e.g., resources/lang/es/messages.php). The package automatically loads the correct locale.

Advanced Workflows

  • Dynamic Language Switching: Integrate with user authentication to persist language preferences:

    // In a User model observer or controller
    event(new LanguageChanged($user->language));
    

    Listen for the event in EventServiceProvider:

    protected $listen = [
        \Aristonis\LanguageSwitcher\Events\LanguageChanged::class => [
            \App\Listeners\UpdateUserLanguage::class,
        ],
    ];
    
  • API Integration: Use middleware to enforce language in API requests:

    Route::middleware(['api', 'language.switcher'])->group(function () {
        // API routes
    });
    
  • Custom Views: Override the default dropdown view by publishing and modifying:

    php artisan vendor:publish --tag=language-switcher.views
    

Gotchas and Tips

Pitfalls

  1. Middleware Order: Ensure LanguageSwitcher middleware runs before LocaleMiddleware in app/Http/Kernel.php to avoid conflicts.

  2. Route Caching: Clear route cache after enabling prefix:

    php artisan route:clear
    
  3. Session vs. Cookie: If using both, ensure config/language-switcher.php has consistent driver settings:

    'driver' => 'cookie', // or 'session'
    
  4. Locale Fallback: The package does not handle missing translations. Always include a fallback locale in your config/app.php:

    'fallback_locale' => 'en',
    
  5. Database Migrations: The package creates a language_switcher_locales table. If you customize it, back up your data before altering the schema.

Debugging

  • Check Current Language: Use Tinker to debug:

    php artisan tinker
    >>> \Aristonis\LanguageSwitcher\Facades\LanguageSwitcher::getCurrentLocale();
    
  • Log Language Switches: Enable logging in config/language-switcher.php:

    'log_switches' => true,
    

Extension Points

  1. Custom Storage: Extend the LocaleRepository to use a custom storage backend (e.g., Redis):

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->bind(
            \Aristonis\LanguageSwitcher\Contracts\LocaleRepository::class,
            \App\Repositories\CustomLocaleRepository::class
        );
    }
    
  2. Language Detection Logic: Override the LanguageDetector contract to implement custom logic (e.g., IP-based detection):

    public function detect(): string
    {
        // Custom logic here
        return $this->getLanguageFromIP();
    }
    
  3. Middleware Logic: Extend the LanguageSwitcher middleware to add pre/post-processing:

    namespace App\Http\Middleware;
    
    use Aristonis\LanguageSwitcher\Middleware\LanguageSwitcher as BaseMiddleware;
    
    class CustomLanguageSwitcher extends BaseMiddleware
    {
        public function handle($request, Closure $next)
        {
            // Custom logic before parent::handle()
            return parent::handle($request, $next);
        }
    }
    

    Register it in Kernel.php:

    \App\Http\Middleware\CustomLanguageSwitcher::class,
    
  4. Blade Directives: Create custom directives by extending the LanguageSwitcherServiceProvider:

    // app/Providers/LanguageSwitcherServiceProvider.php
    public function boot()
    {
        Blade::directive('customLanguage', function () {
            return "<?php echo Aristonis\LanguageSwitcher\Facades\LanguageSwitcher::getCurrentLanguageName(); ?>";
        });
    }
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle