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

mcamara/laravel-localization

Laravel localization helper for multi-language apps: detect browser language, redirect and persist locale (session/cookie), define routes once with locale prefixes, translate routes, optionally hide default locale, plus helpers like language selector. Supports caching and testing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mcamara/laravel-localization
    

    Publish config:

    php artisan vendor:publish --provider="Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider"
    
  2. Register Middleware in app/Http/Kernel.php (or bootstrap/app.php for Laravel 11):

    'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
    'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
    
  3. Configure Locales in config/laravellocalization.php:

    'supportedLocales' => ['en', 'es', 'fr'],
    
  4. Wrap Routes in routes/web.php:

    Route::group(['prefix' => LaravelLocalization::setLocale()], function() {
        Route::get('/', function() { return view('home'); });
    });
    

First Use Case: Localized Routes

  • Access routes via /en/about, /es/about, etc.
  • The package auto-detects locale from URL and sets app()->setLocale().

Implementation Patterns

Core Workflow

  1. Route Grouping:

    Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['localeSessionRedirect']], function() {
        // All localized routes here
    });
    
  2. Middleware Stack:

    • Use localeSessionRedirect for session-based persistence.
    • Use localeCookieRedirect for cookie-based persistence.
    • Add localizationRedirect to hide default locale in URLs.
  3. Dynamic URL Generation:

    // Blade template
    <a href="{{ LaravelLocalization::localizeUrl('/about') }}">About</a>
    

Integration Tips

  • View Localization: Store views in resources/views/{locale}/ and use localeViewPath middleware.
  • Form Actions: Always use LaravelLocalization::localizeUrl() for form actions to avoid redirects.
  • SEO Optimization: Use hideDefaultLocaleInURL to avoid duplicate content issues.

Example: Language Switcher

@foreach(LaravelLocalization::getSupportedLocales() as $locale)
    <a href="{{ LaravelLocalization::localizeUrl('/', $locale) }}">
        {{ LaravelLocalization::getCurrentLocaleNative($locale) }}
    </a>
@endforeach

Gotchas and Tips

Common Pitfalls

  1. POST Requests:

    • Ensure form actions use localizeUrl() to avoid MethodNotAllowedHttpException.
    • Example:
      <form action="{{ LaravelLocalization::localizeUrl('/submit') }}" method="POST">
      
  2. Validation Messages:

    • If validation messages appear in the default locale, ensure:
      • The lang file exists for the locale in resources/lang/{locale}/validation.php.
      • The locale is correctly set via app()->setLocale().
  3. Route Caching:

    • Clear route cache after adding new localized routes:
      php artisan route:clear
      
  4. URL Collisions:

    • Avoid custom locale keys that conflict with existing ones (e.g., uk for en-GB).
    • Use localesMapping to handle custom URL segments.

Debugging Tips

  • Check Locale:
    dd(app()->getLocale()); // Debug current locale
    
  • Middleware Order: Ensure localize middleware runs before localeSessionRedirect or localeCookieRedirect.
  • Testing: Use LaravelLocalization::setLocale() in tests to mock locales:
    LaravelLocalization::setLocale('es');
    

Extension Points

  1. Custom Locale Detection: Override Mcamara\LaravelLocalization\LanguageNegotiator to add custom logic for locale detection.
  2. Dynamic Locale Switching: Use middleware to force a locale for specific routes:
    Route::group(['middleware' => ['force.locale:fr']], function() { ... });
    
  3. Fallback Locales: Configure supportedLocales with fallback chains:
    'supportedLocales' => [
        'en' => ['en', 'en-US'],
        'es' => ['es', 'en'],
    ],
    

Performance

  • Caching: Enable route caching for better performance:
    php artisan route:cache
    
  • UTF-8 Suffix: Adjust utf8suffix in config if using non-standard servers (e.g., CentOS).
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport