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

bibrokhim/laravel-language-header

Laravel middleware/package that detects and sets the application locale from the HTTP Accept-Language header. Helps automatically localize responses based on the user’s browser or client language preferences, with simple Laravel integration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bibrokhim/laravel-language-header
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Bibrokhim\LanguageHeader\LanguageHeaderServiceProvider"
    
  2. Basic Configuration Edit config/language-header.php to define:

    • Allowed language headers (e.g., Accept-Language, X-Locale)
    • Supported locales (e.g., ['en', 'fr', 'es'])
    • Default fallback locale (e.g., 'en')
  3. First Use Case In app/Http/Kernel.php, add the middleware to the $middleware array:

    \Bibrokhim\LanguageHeader\Middleware\SetLocaleFromHeader::class,
    

First Request Handling

  • Send a request with a language header (e.g., Accept-Language: fr-FR).
  • The middleware parses the header, sets the app locale (e.g., app()->setLocale('fr')), and adds the X-Locale header to responses.

Implementation Patterns

Workflow Integration

  1. Request Processing

    • The middleware runs before route resolution, ensuring locale is set early.
    • Use app()->getLocale() in controllers/views to access the dynamic locale.
  2. Fallback Logic

    • If the header is malformed or unsupported, the config-defined fallback locale is used.
    • Example: Accept-Language: xx-YY → falls back to config('language-header.default').
  3. Response Headers

    • Automatically appends X-Locale: {locale} to all responses (useful for APIs or frontend JS detection).
    • Disable via config: 'add_locale_header' => false.
  4. Testing

    • Mock headers in tests:
      $response = $this->withHeaders(['Accept-Language' => 'fr-FR'])->get('/');
      $this->assertEquals('fr', app()->getLocale());
      

Advanced Patterns

  • Dynamic Locale Switching Combine with route middleware to override locale per route:

    Route::middleware(['set.locale' => 'fr'])->group(...);
    

    (Requires custom middleware extending SetLocaleFromHeader.)

  • API Versioning Use the X-Locale header for API versioning (e.g., /v1 + X-Locale: es → Spanish v1).

  • Frontend Integration Read X-Locale in JavaScript to set UI language:

    const locale = document.querySelector('meta[name="locale"]').content;
    // or fetch from headers in SPAs.
    

Gotchas and Tips

Pitfalls

  1. Header Parsing Quirks

    • The package uses PHP’s AcceptLanguage::parse() (Laravel 9+). Edge cases:
      • Accept-Language: en-US,fr;q=0.9 → defaults to en.
      • Empty/missing headers → uses fallback.
    • Fix: Validate headers early in middleware if strict parsing is needed.
  2. Caching Conflicts

    • Locale changes mid-request (e.g., due to header parsing) may break cached views.
    • Solution: Use Cache::forget('view::*') or disable caching for dynamic locales.
  3. Middleware Order

    • Place SetLocaleFromHeader before StartSession to avoid session bloat with locale data.
    • Place after TrustProxies if behind a proxy (to read original headers).
  4. Config Overrides

    • The package respects Laravel’s App::setLocale() but doesn’t override it.
    • Tip: Use config(['language-header.default' => 'es']) to change defaults dynamically.

Debugging

  • Check Headers Log parsed headers in middleware:
    \Log::debug('Parsed locale:', ['locale' => $locale]);
    
  • Validate Config Ensure supported_locales matches your app’s config/app.locales.
  • Test Edge Cases
    • Empty headers: Accept-Language:
    • Invalid locales: Accept-Language: xx-YY
    • Multiple locales: Accept-Language: en-US,fr-FR;q=0.8

Extension Points

  1. Custom Header Names Override config('language-header.header_name') to use X-Custom-Locale.

  2. Locale Resolution Logic Extend the middleware:

    class CustomLocaleMiddleware extends SetLocaleFromHeader {
        protected function resolveLocaleFromRequest(): string {
            // Custom logic (e.g., URL param fallback)
            return parent::resolveLocaleFromRequest() ?? request()->route('locale');
        }
    }
    
  3. Response Header Modification Hook into Illuminate\Http\Middleware\AppendLocaleHeader to modify the X-Locale value:

    public function handle($request, Closure $next) {
        $response = $next($request);
        $response->headers->set('X-Locale', strtoupper(app()->getLocale()));
        return $response;
    }
    
  4. Locale Negotiation Combine with laravel-i18n-routing for URL-based fallback:

    // config/language-header.php
    'fallback_to_route_locale' => 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.
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
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