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. Configure Locales (config/laravellocalization.php):

    'supportedLocales' => ['en', 'es', 'fr'],
    'defaultLocale' => 'en',
    'hideDefaultLocaleInURL' => true,
    
  3. Register Middleware (app/Http/Kernel.php or bootstrap/app.php):

    'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
    'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
    
  4. Wrap Routes (routes/web.php):

    Route::group(['prefix' => LaravelLocalization::setLocale()], function() {
        Route::get('/', function() { return view('home'); });
        Route::get('/about', function() { return view('about'); });
    });
    
  5. First Use Case: Access / → Auto-detects locale (if useAcceptLanguageHeader is true) or redirects to /en. Access /es/about → Shows Spanish version of /about.


Implementation Patterns

Core Workflow

  1. Route Grouping: Always wrap localized routes in LaravelLocalization::setLocale().

    Route::group(['prefix' => LaravelLocalization::setLocale()], function() {
        // All localized routes here
    });
    
  2. Middleware Stack: Use these middleware in order for optimal behavior:

    'middleware' => [
        'localeSessionRedirect', // Persists locale in session
        'localizationRedirect',  // Handles default locale hiding
        'localeViewPath'         // Sets view path to `/resources/views/{locale}/`
    ]
    
  3. URL Generation:

    • Localized URLs (current locale):
      {{ LaravelLocalization::localizeUrl('/about') }}  // e.g., `/es/about`
      
    • Specific Locale:
      {{ LaravelLocalization::getLocalizedURL('fr') }}  // e.g., `/fr/about`
      
    • Clean URLs (remove locale):
      {{ LaravelLocalization::getNonLocalizedURL('/es/about') }}  // `/about`
      
  4. Dynamic Route Parameters: Use getURLFromRouteNameTranslated for routes with parameters:

    <a href="{{ LaravelLocalization::getURLFromRouteNameTranslated(
        App::currentLocale(),
        'routes.post',
        ['id' => $post->id]
    ) }}">
        {{ $post->title }}
    </a>
    
  5. View Localization:

    • Organize views in resources/views/{locale}/ (e.g., es/home.blade.php).
    • Register localeViewPath middleware to auto-switch view paths.
  6. Language Switcher: Use getLocalesOrder() to render a dropdown:

    @foreach(LaravelLocalization::getLocalesOrder() as $locale)
        <a href="{{ LaravelLocalization::getLocalizedURL($locale) }}">
            {{ LaravelLocalization::getLocaleNativeName($locale) }}
        </a>
    @endforeach
    

Integration Tips

  • Form Actions: Always localize form actions to avoid redirect loops:
    <form action="{{ LaravelLocalization::localizeUrl('/submit') }}" method="POST">
    
  • API Routes: Exclude API routes from localization if stateless:
    Route::prefix('api')->group(function() {
        // Non-localized API routes
    });
    
  • Caching: Disable route caching (php artisan route:cache) if using this package (dynamic routes). Use LaravelLocalization::disableCache() in AppServiceProvider for testing.

Gotchas and Tips

Pitfalls

  1. Route Caching Conflict:

  2. POST Requests:

    • Issue: POST requests may redirect if locale is missing.
    • Fix: Ensure all form actions include the locale:
      <form action="{{ LaravelLocalization::localizeUrl('/submit') }}" method="POST">
      
  3. Validation Messages:

    • Issue: Validation errors appear in the default locale.
    • Fix: Override resources/lang/{locale}/validation.php or use:
      $validator->setAttributeNames([
          'field' => trans('validation.attributes.field'),
      ]);
      
  4. Duplicate Content (SEO):

    • Issue: Search engines may index /en/page and /page as duplicates.
    • Fix: Use LaravelLocalizationRedirectFilter middleware to canonicalize URLs.
  5. Session/Cookie Conflicts:

    • Issue: Locale session/cookie may persist incorrectly.
    • Fix: Clear session/cookie manually:
      session()->forget('locale');
      // or
      Cookie::queue(Cookie::forget('locale'));
      

Debugging Tips

  • Check Current Locale:
    dd(LaravelLocalization::getCurrentLocale());
    
  • Inspect Middleware Order: Ensure localize middleware runs before localeSessionRedirect or localeCookieRedirect.
  • Test Locale Detection: Override useAcceptLanguageHeader temporarily in config for testing:
    'useAcceptLanguageHeader' => false,
    

Extension Points

  1. Custom Locale Detection: Extend Mcamara\LaravelLocalization\Detectors\DetectorInterface to add logic (e.g., user role-based locales).

  2. Dynamic Locale Switching: Override AppServiceProvider::boot() to force a locale:

    LaravelLocalization::setForcedLocale('es');
    
  3. View Path Overrides: Modify localeViewPath middleware to use custom paths:

    public function handle($request, Closure $next) {
        View::addNamespace('custom', resource_path('views/custom/' . app()->getLocale()));
        return $next($request);
    }
    
  4. URL Ignore Patterns: Exclude specific routes from localization in config:

    'urlsIgnored' => [
        'admin/*',
        'api/*',
    ],
    

Performance

  • Disable Cache in Production: If using dynamic routes, disable caching for critical paths:
    LaravelLocalization::disableCache();
    
  • Prefer Cookie Over Session: For better performance, use localeCookieRedirect instead of localeSessionRedirect if cookies are acceptable.

Testing

  • Mock Locale:
    LaravelLocalization::setForcedLocale('fr');
    
  • Test Redirects:
    $response = $this->get('/about');
    $response->assertRedirect('/fr/about');
    
  • Isolate Locale Logic: Use LaravelLocalization::disableCache() in tests to avoid stale cached routes.

```markdown
### Common Issues (From README)
| Issue                          | Solution                                                                 |
|--------------------------------|--------------------------------------------------------------------------|
| POST not working               | Localize form actions: `localizeUrl('/submit')`                          |
| MethodNotAllowedHttpException  | Ensure middleware order: `localize` → `localeSessionRedirect`            |
| Validation in default locale   | Override `resources/lang/{locale}/validation.php` or use `setAttributeNames` |
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony