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

Config Laravel Package

laravel-lang/config

Language configuration companion for the Laravel Lang ecosystem. Provides shared config resources used across Laravel Lang packages, with Composer installation and MIT licensing. Includes contribution guidelines and ways to support the project.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require laravel-lang/config
    

    Publish the configuration files:

    php artisan vendor:publish --provider="LaravelLangConfigServiceProvider"
    
  2. Basic Configuration:

    • Locate the published config file at config/laravel-lang.php.
    • Define your locale-specific configurations in config/locales/{locale}.php (e.g., config/locales/en.php, config/locales/es.php).
  3. First Use Case: Access a locale-specific config value:

    // Default fallback to 'en' if 'es' is not found
    $value = config('app.locale_aware_setting');
    

    Example structure in config/locales/es.php:

    return [
        'locale_aware_setting' => 'Valor específico en español',
    ];
    
  4. Set Default Locale: Ensure APP_LOCALE is set in your .env file:

    APP_LOCALE=en
    

Implementation Patterns

Usage Patterns

  1. Locale-Specific Configs: Organize configs by locale in config/locales/{locale}.php:

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

    Access via:

    $endpoint = config('services.stripe.endpoint'); // Uses 'es' locale
    
  2. Fallback Chain: The package automatically falls back through a chain (e.g., es_MXesen). Define the chain in config/laravel-lang.php:

    'fallback_locales' => ['es', 'en'],
    
  3. Dynamic Locale Switching: Override the locale per request (e.g., for API endpoints):

    // In a middleware or controller
    app('laravel-lang')->setLocale('fr');
    $value = config('app.some_setting'); // Now uses 'fr' locale
    
  4. Route-Specific Configs: Use the config parameter in route definitions (requires laravel-lang/routes package):

    Route::get('/settings', function () {
        return config('user.settings'); // Locale-aware
    })->middleware('locale');
    
  5. Model-Specific Configs: Extend Eloquent models with locale-aware attributes (requires laravel-lang/models):

    use LaravelLang\Config\Traits\HasConfig;
    
    class User extends Model
    {
        use HasConfig;
    
        protected $configPath = 'users';
    }
    

    Define configs in config/locales/{locale}/users.php:

    return [
        'greeting' => '¡Hola, {name}!', // 'es' locale
    ];
    

    Access via:

    $user->config('greeting'); // Returns localized greeting
    

Workflows

  1. Development Workflow:

    • Edit config/locales/{locale}.php files.
    • Run php artisan config:clear to refresh configs (or use php artisan config:cache in production).
    • Test locale switching with:
      app('laravel-lang')->setLocale('de');
      
  2. Translation Workflow:

    • Use the package alongside laravel-lang/manager for translation files.
    • Sync configs with translation keys where applicable.
  3. CI/CD Integration:

    • Add a step to clear the config cache after merging locale updates:
      # .github/workflows/deploy.yml
      - run: php artisan config:clear
      
  4. Testing:

    • Mock configs in tests:
      config(['app.locale_aware_setting' => 'Test Value']);
      
    • Test fallback behavior:
      $this->app->instance('laravel-lang', \Mockery::mock([
          'getLocale' => 'es_MX',
      ]));
      

Integration Tips

  1. Service Providers: Bind locale-specific configs in a service provider:

    public function boot()
    {
        $this->app['config']->shouldCache(false); // Disable caching during development
    }
    
  2. Blade Templates: Use @config directive (if supported) or access directly:

    <h1>{{ config('app.locale_aware_setting') }}</h1>
    
  3. APIs: Set the locale via headers or query params:

    // Middleware
    public function handle($request, Closure $next)
    {
        $locale = $request->header('Accept-Language') ?? 'en';
        app('laravel-lang')->setLocale($locale);
        return $next($request);
    }
    
  4. Environment-Specific Configs: Override configs per environment (e.g., config/locales/es/production.php):

    // config/locales/es/production.php
    return [
        'maintenance_mode' => true,
    ];
    

Gotchas and Tips

Pitfalls

  1. Cache Invalidation:

    • Issue: Forgetting to run php artisan config:clear after updating locale files.
    • Fix: Automate cache clearing in CI/CD or use php artisan config:cache in production with a post-update hook.
    • Tip: Add a custom Artisan command to clear configs and cache:
      php artisan lang:clear
      
  2. Locale Fallback Misconfiguration:

    • Issue: Fallback chain not working as expected (e.g., es_MX not falling back to es).
    • Fix: Verify fallback_locales in config/laravel-lang.php:
      'fallback_locales' => ['es', 'en'],
      
    • Debug: Check the active locale with:
      dd(app('laravel-lang')->getLocale());
      
  3. File Structure Confusion:

    • Issue: Configs not loading due to incorrect file paths.
    • Fix: Ensure files are placed in config/locales/{locale}.php (not config/{locale}.php).
    • Tip: Use the initialize() method to load configs from a custom path:
      \LaravelLang\Config\Facades\LaravelLang::initialize([
          'path' => base_path('custom-configs/locales'),
      ]);
      
  4. Middleware Conflicts:

    • Issue: Locale middleware overriding configs unexpectedly.
    • Fix: Ensure middleware sets the locale before configs are accessed:
      // Kernel.php
      protected $middlewareGroups = [
          'web' => [
              \App\Http\Middleware\SetLocale::class,
              // Other middleware...
          ],
      ];
      
  5. Namespace Collisions:

    • Issue: Config keys conflicting with Laravel’s default configs.
    • Fix: Prefix locale-specific keys:
      // Avoid:
      'app.name' => 'Nombre App'
      // Use:
      'locale.app.name' => 'Nombre App'
      
  6. Dynamic Locale Switching:

    • Issue: Locale changes not persisting across requests.
    • Fix: Store the locale in the session or use a cookie:
      // Middleware
      $request->session()->put('locale', $locale);
      
    • Tip: Use the locale session driver for persistence.

Debugging

  1. Check Loaded Configs: Dump the merged configs to debug:

    dd(app('config')->all());
    
  2. Verify Locale: Log the active locale:

    \Log::debug('Active locale:', ['locale' => app('laravel-lang')->getLocale()]);
    
  3. Fallback Debugging: Test fallback behavior:

    $this->app->instance('laravel-lang', \Mockery::mock([
        'getLocale' => 'es_MX',
    ]));
    $value = config('app.some_setting');
    
  4. File Permissions: Ensure the bootstrap/cache directory is writable:

    chmod -R 775 bootstrap/cache
    

Tips

  1. Use config() Helper: Leverage Laravel’s built-in config() helper for type safety and autoloading:

    $value = config('app.locale_aware_setting', 'default_value');
    
  2. Environment-Specific Locales: Set the default locale per environment in .env:

    APP_LOCALE=en
    APP_LOCALE_TEST=es
    
  3. Custom Facade: Create a facade for cleaner syntax:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        app()->bind('localeConfig', function () {
            return new class {
                public
    
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
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