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 Config Writer Laravel Package

axdlee/laravel-config-writer

Write safely to Laravel config PHP files (Laravel 5.3+), updating nested keys while preserving formatting, comments, and advanced settings. Supports strings, ints, booleans, and single-level arrays. Includes Laravel service provider and standalone Rewrite class.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require axdlee/laravel-config-writer
    
  2. Register Provider: Add to config/app.php under 'providers':
    Axdlee\Config\ConfigServiceProvider::class,
    
  3. First Use Case: Write to a config file directly:
    use Illuminate\Support\Facades\Config;
    Config::write('app.url', 'https://example.com');
    
    This updates config/app.php while preserving comments and structure.

Implementation Patterns

Core Workflows

  1. Dynamic Configuration Updates: Use Config::write() to modify config values at runtime (e.g., feature flags, environment-specific settings):

    // Update a nested key
    Config::write('services.stripe.key', env('STRIPE_KEY'));
    
    // Update an array
    Config::write('mail.from.address', ['address' => 'contact@example.com']);
    
  2. Environment-Specific Configs: Override configs per environment (e.g., config/local.php):

    if (app()->environment('local')) {
        Config::write('app.debug', true);
    }
    
  3. Non-Laravel Usage: Use the standalone Rewrite class for CLI scripts or non-Laravel PHP:

    $rewriter = new \Axdlee\Config\Rewrite();
    $rewriter->toFile('config/custom.php', [
        'custom.setting' => 'value',
        'nested.key' => ['a', 'b', 'c'],
    ]);
    

Integration Tips

  • Validation: Validate values before writing to avoid corrupting configs:
    $value = request()->input('app.timezone');
    if (in_array($value, ['UTC', 'America/New_York'])) {
        Config::write('app.timezone', $value);
    }
    
  • Backup Configs: Create a backup before writing critical configs:
    file_put_contents('config/app.php.bak', file_get_contents('config/app.php'));
    Config::write('app.url', 'https://new-domain.com');
    
  • Publish Configs: Combine with Laravel’s publishes to manage config files in version control:
    // config/app.php
    'providers' => [
        // ...,
        Axdlee\Config\ConfigServiceProvider::class,
    ],
    

Gotchas and Tips

Pitfalls

  1. File Integrity Risks:

    • Issue: Writing to config files can corrupt them if the structure is malformed (e.g., unclosed PHP tags, syntax errors).
    • Fix: Always test in a staging environment first. Use file_put_contents to verify the file before writing:
      $tempPath = tempnam(sys_get_temp_dir(), 'config_');
      file_put_contents($tempPath, $rewriter->rewrite(file_get_contents('config/app.php'), ['app.url' => 'test']));
      // Validate $tempPath before overwriting.
      
  2. Nested Arrays:

    • Issue: Only single-dimension arrays are supported. Writing multi-dimensional arrays may fail silently.
    • Fix: Flatten arrays or use dot notation for nested keys:
      // Supported
      Config::write('services.stripe.options.timeout', 30);
      
      // Unsupported (may fail)
      Config::write('services.stripe.options', ['timeout' => 30, 'retries' => 3]);
      
  3. Comments and Whitespace:

    • Issue: The package preserves comments but may alter whitespace or formatting.
    • Fix: Use php-cs-fixer or manual cleanup after writing to enforce consistency.
  4. Caching:

    • Issue: Laravel caches configs. Changes via Config::write() may not reflect immediately.
    • Fix: Clear the config cache after writing:
      Config::write('app.debug', true);
      Artisan::call('config:clear');
      

Debugging Tips

  • Log Changes: Log config writes for auditing:
    \Log::info('Config updated', ['key' => 'app.url', 'value' => 'https://example.com']);
    Config::write('app.url', 'https://example.com');
    
  • Verify Output: Compare the original and modified config files:
    $original = file_get_contents('config/app.php');
    $rewriter = new \Axdlee\Config\Rewrite();
    $modified = $rewriter->rewrite($original, ['app.url' => 'test']);
    echo diff($original, $modified); // Use a diff tool or library
    

Extension Points

  1. Custom Rewriters: Extend the Rewrite class to support additional data types (e.g., objects, dates):
    class CustomRewriter extends \Axdlee\Config\Rewrite {
        public function rewrite($content, array $data) {
            // Add support for dates
            foreach ($data as $key => $value) {
                if ($value instanceof \DateTime) {
                    $data[$key] = $value->format('Y-m-d');
                }
            }
            return parent::rewrite($content, $data);
        }
    }
    
  2. Pre/Post-Write Hooks: Use Laravel events to trigger actions before/after writing:
    // In a service provider
    event(new \Axdlee\Config\WritingStarted('app.url'));
    Config::write('app.url', 'https://example.com');
    event(new \Axdlee\Config\WritingCompleted('app.url'));
    
  3. Environment-Specific Writers: Create environment-specific writer instances:
    $localWriter = new \Axdlee\Config\Rewrite();
    $localWriter->setEnvironment('local');
    $localWriter->toFile('config/local.php', ['app.debug' => 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