Weave 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

Config Laravel Package

laravel-lang/config

Official configuration package for Laravel Lang, providing shared settings and defaults used across its localization tools so you can manage language files and locales consistently in Laravel apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require laravel-lang/config
    
  2. Publish the configuration files (if extending defaults):

    php artisan vendor:publish --provider="LaravelLangConfigServiceProvider"
    

    This creates config/laravel-lang.php with default settings.

  3. Register the service provider (if not auto-discovered): Add to config/app.php:

    'providers' => [
        LaravelLangConfigServiceProvider::class,
    ],
    
  4. Define locale-specific configs: Create files in config/locales/ (e.g., en.php, es.php):

    // config/locales/en.php
    return [
        'app' => [
            'name' => 'My App (English)',
            'timezone' => 'America/New_York',
        ],
        'services' => [
            'stripe' => [
                'endpoint' => 'https://api.stripe.com/v1',
            ],
        ],
    ];
    
  5. Use configs with fallbacks:

    // Automatically falls back to 'en' if 'es_MX' is missing
    $appName = config('app.name', 'default');
    

First Use Case: Localized API Endpoints

// config/locales/es.php
return [
    'services' => [
        'stripe' => [
            'endpoint' => 'https://api.stripe.com/es/v1', // Spanish endpoint
        ],
    ],
];

// In your controller:
$endpoint = config('services.stripe.endpoint'); // Resolves to Spanish endpoint for es_MX users

Implementation Patterns

1. Locale-Aware Configuration Loading

Workflow:

  • Store configs in config/locales/{locale}.php.
  • Use config() helper with automatic fallback:
    // Falls back: es_MX → es → en → default
    $value = config('path.to.key');
    

Example:

// config/locales/es_MX.php
return [
    'legal' => [
        'terms_url' => 'https://example.com/terms-es_mx',
    ],
];

// config/locales/es.php (fallback)
return [
    'legal' => [
        'terms_url' => 'https://example.com/terms-es',
    ],
];

// Usage:
$termsUrl = config('legal.terms_url'); // Resolves to es_MX → es

2. Dynamic Locale Switching

Use Case: Override configs per request (e.g., admin panel). Pattern:

use LaravelLang\Config\Facades\Config;

// Set locale dynamically
Config::setLocale('fr');

// Access configs
$name = config('app.name'); // Loads from config/locales/fr.php

Integration with Middleware:

// app/Http/Middleware/SetLocale.php
public function handle($request, Closure $next) {
    Config::setLocale($request->header('Accept-Language') ?? 'en');
    return $next($request);
}

3. Route-Specific Configs

Use Case: Localize route names or middleware per locale. Pattern:

// config/laravel-lang.php
'routes' => [
    'prefix' => 'locales',
    'meta' => [
        'en' => ['prefix' => 'en', 'middleware' => ['web']],
        'es' => ['prefix' => 'es', 'middleware' => ['throttle:60']],
    ],
],

// Usage in routes/web.php
Route::group([
    'middleware' => config('laravel-lang.routes.meta.'.$locale.'.middleware'),
], function () {
    // ...
});

4. Model-Specific Localization

Use Case: Localize model attributes (e.g., name field). Pattern:

// config/laravel-lang.php
'models' => [
    'directory' => 'app/Models/Locales',
    'suffix' => 'Locale',
],

// Create localized models:
php artisan make:model PostLocale --locale=es
php artisan make:model PostLocale --locale=fr

// Usage:
$post = Post::withLocale('es')->find(1);
echo $post->name; // Loads from PostLocale::class

5. Environment-Specific Overrides

Use Case: Merge configs based on environment (e.g., local, staging). Pattern:

// config/locales/en_staging.php
return [
    'debug' => true,
    'services' => [
        'stripe' => [
            'endpoint' => env('STRIPE_STAGING_ENDPOINT'),
        ],
    ],
];

6. Caching and Performance

Best Practices:

  • Cache configs: Laravel caches configs by default. Clear with:
    php artisan config:clear
    
  • Avoid runtime file loading: Prefer config() over direct file includes.
  • Use config_cache: For production, generate a config.php cache:
    php artisan config:cache
    

Gotchas and Tips

Pitfalls

  1. Fallback Chain Issues:

    • Problem: Configs may silently fall back to null if the chain is broken.
    • Fix: Always provide a default value:
      $value = config('path.to.key', 'default');
      
    • Debug: Check the fallback order in config/laravel-lang.php:
      'fallback_locales' => ['es', 'en'],
      
  2. File Naming Conflicts:

    • Problem: Overlapping keys between locales (e.g., en and es both define app.name).
    • Fix: Use explicit paths or merge strategies:
      // config/laravel-lang.php
      'merge_strategy' => 'overwrite', // or 'deep_merge'
      
  3. Cache Invalidation:

    • Problem: Changes to config/locales/ require config:clear.
    • Fix: Automate with Git hooks or use config:cache in production:
      php artisan config:cache --env=production
      
  4. Locale Detection:

    • Problem: Accept-Language headers may not match user expectations.
    • Fix: Combine with user preferences:
      $locale = auth()->user()->locale ?? request()->header('Accept-Language');
      Config::setLocale($locale);
      
  5. Middleware Order:

    • Problem: Locale-setting middleware must run before config access.
    • Fix: Place it early in $middlewareGroups['web']:
      'middleware' => [
          \App\Http\Middleware\SetLocale::class,
          // ...
      ],
      

Debugging Tips

  1. Inspect Loaded Configs:

    dd(config('laravel-lang'));
    

    or dump the resolved locale:

    dd(Config::getLocale());
    
  2. Check Fallback Chain:

    $chain = Config::getFallbackLocales();
    // Output: ['es_MX', 'es', 'en']
    
  3. Validate Locale Files:

    • Ensure files are named {locale}.php (e.g., es_MX.php).
    • Use php artisan config:clear after edits.
  4. Override Configs Temporarily:

    Config::set('app.name', 'Test', 'test');
    // Only affects the 'test' locale.
    

Extension Points

  1. Custom Merge Strategies: Extend the LaravelLang\Config\MergeStrategy trait to handle complex merges:

    // app/Providers/LaravelLangServiceProvider.php
    public function boot() {
        Config::extendMergeStrategy(function ($source, $destination) {
            // Custom logic here
            return array_merge_recursive($destination, $source);
        });
    }
    
  2. Dynamic Locale Providers: Replace the default locale detection:

    Config::setLocaleProvider(function () {
        return auth()->user()->preferred_locale ?? 'en';
    });
    
  3. Add New Config Sources: Register additional directories in config/laravel-lang.php:

    'paths' => [
        'locales' => [app_path('Configs/Locales')],
    ],
    
  4. Integration with Laravel Data: Use Spatie\LaravelData for typed configs:

    use Spatie\LaravelData\Data;
    
    class AppConfig extends Data {
        public function __construct(
            public string $name,
            public array $services,
        ) {}
    }
    
    $config = AppConfig::from(config('app'));
    

Pro Tips

  1. Use for Feature Flags:
    // config/locales/en.php
    return [
        'features' => [
            'new_ui' => 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.
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin