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

movemoveapp/laravel-localization

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require movemoveapp/laravel-localization
    

    Publish the config file:

    php artisan vendor:publish --provider="Movemoveapp\Localization\LocalizationServiceProvider"
    
  2. Configure config/localization.php:

    'locales' => [
        'en' => [
            'name' => 'English',
            'url' => 'en',
            'flag' => 'gb',
            'native' => 'English',
        ],
        'es' => [
            'name' => 'Español',
            'url' => 'es',
            'flag' => 'es',
            'native' => 'Español',
        ],
        'ru' => [
            'name' => 'Русский',
            'url' => 'ru',
            'flag' => 'ru',
            'native' => 'Русский',
        ],
    ],
    
  3. First Use Case:

    • Detect language from browser:
      use Movemoveapp\Localization\Facades\Localization;
      
      $locale = Localization::getCurrentLocale(); // e.g., 'en'
      
    • Redirect based on domain: Configure domain_locales in config/localization.php:
      'domain_locales' => [
          'example.es' => 'es',
          'example.ru' => 'ru',
          'en.example.com' => 'en',
      ],
      
      Now, visiting example.es will automatically redirect to the Spanish locale.

Implementation Patterns

Core Workflows

1. Locale Detection and Routing

  • Automatic detection: The package detects the locale from the browser's Accept-Language header or session/cookie.
    Localization::detectLocale(); // Auto-detects and sets locale
    
  • Route definitions: Define routes once in routes/web.php:
    Route::get('/home', 'HomeController@index')->name('home');
    
    The package handles locale-specific URLs (e.g., /en/home, /es/inicio).

2. Locale Switching

  • Manual switching:
    Localization::setLocale('es'); // Force locale to Spanish
    
  • URL-based switching: Add a locale switcher link in your Blade template:
    @foreach(Localization::getSupportedLocales() as $locale)
        <a href="{{ Localization::getLocalizedURL($locale, route('home')) }}">
            {{ $locale['native'] }}
        </a>
    @endforeach
    

3. Translatable Routes

  • Dynamic route generation:
    $url = Localization::getLocalizedURL('es', route('home')); // e.g., /es/inicio
    
  • Locale-aware redirects:
    return Localization::redirectLocalized('es', route('home'));
    

4. Middleware Integration

  • Force locale for specific routes:
    Route::middleware(['locale' => 'es'])->group(function () {
        Route::get('/es/privacy', 'PrivacyController@index');
    });
    
  • Global locale detection: Add to app/Http/Kernel.php:
    protected $middlewareGroups = [
        'web' => [
            // ...
            \Movemoveapp\Localization\Middleware\DetectLocale::class,
        ],
    ];
    

5. Domain-Based Localization

  • Configure domain mappings:
    'domain_locales' => [
        'example.es' => 'es',
        'example.ru' => 'ru',
        'en.example.com' => 'en',
    ],
    
  • Automatic redirects: Visiting example.es will redirect to /es/ (or your configured base URL for the locale).

Integration Tips

1. Blade Directives

  • Locale-aware links:
    <a href="{{ localized(route('home')) }}">
        {{ __('Home') }}
    </a>
    
    Add to AppServiceProvider:
    Blade::directive('localized', function ($expression) {
        return "<?php echo Movemoveapp\Localization\Facades\Localization::getLocalizedURL(Localization::getCurrentLocale(), {$expression}); ?>";
    });
    

2. Session/Cookie Persistence

  • Save locale preference:
    Localization::saveLocaleToSession('es');
    
  • Detect from session:
    Localization::detectLocaleFromSession();
    

3. Fallback Locales

  • Configure fallback locales in config/localization.php:
    'fallback_locale' => 'en',
    'fallback_locales' => ['en', 'es'],
    

4. Testing

  • Mock locale detection:
    $this->app->instance('request', $request = Mockery::mock());
    $request->shouldReceive('get')->with('locale')->andReturn('es');
    

Gotchas and Tips

Pitfalls

1. Domain Locale Conflicts

  • Issue: If a domain maps to multiple locales (e.g., example.com and en.example.com), the package prioritizes the most specific match.
  • Fix: Ensure domain mappings are mutually exclusive or use subdomains explicitly (e.g., en.example.com vs. example.com).

2. Route Caching

  • Issue: After adding locale support, cached routes may break.
  • Fix: Clear route cache:
    php artisan route:clear
    
    Or disable caching during development:
    'cache_routes' => env('APP_ENV') !== 'local',
    

3. Session/Cookie Conflicts

  • Issue: If using multiple localization packages, session/cookie keys may clash.
  • Fix: Customize the session/cookie key in config:
    'session_key' => 'laravel_localization_locale',
    'cookie_key' => 'laravel_localization_locale',
    

4. Translatable Routes and Middleware

  • Issue: Middleware like auth may not work as expected with locale-aware routes.
  • Fix: Ensure middleware is applied to the correct route group or use the localized helper for URLs.

5. URL Generation in Tests

  • Issue: route() may not respect the current locale in tests.
  • Fix: Manually set the locale before generating URLs:
    Localization::setLocale('es');
    $url = route('home'); // Now returns `/es/inicio`
    

Debugging Tips

1. Check Current Locale

dd(Localization::getCurrentLocale());

2. Inspect Detected Locale

dd(Localization::detectLocale());

3. Log Locale Switches

Add to AppServiceProvider:

Localization::setLocaleChangedCallback(function ($locale) {
    \Log::info("Locale changed to: {$locale}");
});

4. Validate Config

Ensure locales and domain_locales are correctly configured. Test with:

php artisan localization:list

Extension Points

1. Custom Locale Detection

Override the default detection logic by extending the DetectLocale middleware:

namespace App\Http\Middleware;

use Closure;
use Movemoveapp\Localization\Middleware\DetectLocale as BaseDetectLocale;

class CustomDetectLocale extends BaseDetectLocale
{
    protected function detectLocale()
    {
        // Custom logic here
        return 'es'; // Force Spanish
    }
}

Register in app/Http/Kernel.php:

protected $middleware = [
    \App\Http\Middleware\CustomDetectLocale::class,
];

2. Dynamic Locale Loading

Load locales dynamically (e.g., from a database):

Localization::setLocales($dynamicLocales);

3. Custom Redirect Logic

Override the redirect behavior:

Localization::setRedirectCallback(function ($locale, $url) {
    return redirect()->to($url)->withCookie(cookie('locale', $locale, 30));
});

4. Locale-Specific Views

Use Blade's @lang directive or create locale-specific view paths:

// In config/filesystems.php
'views' => [
    'en' => resource_path('views/en'),
    'es' => resource_path('views/es'),
],

Then override the view resolver in AppServiceProvider:

$this->app['view']->addNamespace('en', resource
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager