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 package for i18n: detect locale from browser, redirect and persist locale via session/cookie, define routes once with localized URL prefixes and translatable routes, optional hiding of default locale, plus helpers like language selectors.

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,
    'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
    
  3. Configure Locales in config/laravellocalization.php:

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

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

First Use Case

  • Detect User Locale: Access / → Redirects to /en/ (or detected locale) via localizationRedirect middleware.
  • Generate Localized Links: Use LaravelLocalization::localizeUrl('/contact') in Blade templates.

Implementation Patterns

Core Workflow

  1. Route Grouping:

    Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => ['localeSessionRedirect']], function() {
        Route::get('/about', [AboutController::class, 'index']);
    });
    
    • Automatically generates /en/about, /es/about, etc.
  2. Middleware Stack:

    • localize: Dynamically routes based on URL locale.
    • localeSessionRedirect/localeCookieRedirect: Persist locale preference.
    • localizationRedirect: Hide default locale in URLs (e.g., / instead of /en/).
  3. View Localization:

    • Use localeViewPath middleware to load views from resources/views/{locale}/.
    • Example: resources/views/en/home.blade.php for English.

Integration Tips

  • Form Actions:
    <form action="{{ LaravelLocalization::localizeUrl(route('contact.form')) }}" method="POST">
    
  • Dynamic Locale Switching:
    <a href="{{ LaravelLocalization::localizeUrl('/') }}?locale=es">Español</a>
    
  • API Routes: Exclude from localization:
    Route::prefix('api')->group(function() {
        Route::middleware('api')->group(base_path('routes/api.php'));
    });
    

Testing

  • Force Locale:
    $this->actingAsUser()->withHeaders(['Accept-Language' => 'fr']);
    
  • Mock Middleware:
    $this->app->instance(\Mcamara\LaravelLocalization\Facades\LaravelLocalization::class, $mock);
    

Gotchas and Tips

Pitfalls

  1. Route Caching:

    • Issue: php artisan route:cache fails due to dynamic routes.
    • Workaround: Disable caching or use niels-numbers/laravel-localizer for static routes.
  2. POST Requests:

    • Issue: Forms may redirect if locale is missing.
    • Fix: Always localize form actions:
      <form action="{{ LaravelLocalization::localizeUrl(route('submit.form')) }}">
      
  3. Validation Messages:

    • Issue: Messages appear in default locale.
    • Fix: Use LaravelLocalization::setFallbackLocale() or ensure app.php config:
      'fallback_locale' => LaravelLocalization::getCurrentLocale(),
      
  4. SEO Duplicates:

    • Risk: /en/page and /page may return same content.
    • Solution: Use hideDefaultLocaleInURL + canonical tags.

Debugging Tips

  • Check Locale:
    dd(LaravelLocalization::getCurrentLocale());
    
  • Inspect Redirects:
    • Temporarily disable middleware to isolate issues:
      'middleware' => ['localize'], // Remove redirect middleware
      
  • URL Generation:
    • Verify with:
      LaravelLocalization::getLocalizedURL('es', route('home'));
      

Extension Points

  1. Custom Locale Detection: Override AppServiceProvider:

    LaravelLocalization::setLocaleResolver(function() {
        return request()->input('locale') ?: config('app.locale');
    });
    
  2. Locale-Specific Assets: Use middleware to set asset paths:

    LaravelLocalization::onLocaleChanged(function($locale) {
        view()->share('assetLocale', $locale);
    });
    
  3. Fallback Logic: Extend supportedLocales to include fallbacks:

    'supportedLocales' => [
        'en' => ['en', 'en_US', 'en_GB'],
        'es' => ['es', 'es_ES', 'es_MX'],
    ],
    

Configuration Quirks

  • urlsIgnored: Exclude specific routes (e.g., API):
    'urlsIgnored' => [
        'api/*',
        'admin/*',
    ],
    
  • UTF-8 Suffix: For non-standard servers:
    'utf8suffix' => true,
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope