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

Toml Laravel Package

yosymfony/toml

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require yosymfony/toml
    

    No additional configuration is required—this is a drop-in parser with zero dependencies.

  2. First Use Case: Parsing a TOML File

    use Yosymfony\Toml\Toml;
    
    $toml = file_get_contents('config.toml');
    $data = Toml::parse($toml);
    
    // Outputs: `['database' => ['host' => 'localhost', 'port' => 3306]]`
    print_r($data);
    
  3. Where to Look First

    • API Docs: Focus on Toml::parse() (string input) and Toml::parseFile() (file path).
    • Edge Cases: Test with nested tables, arrays, and special values (e.g., inline_tables, dates).
    • Validation: Use Toml::validate() to check for syntax errors before parsing.

Implementation Patterns

Common Workflows

  1. Configuration Management

    // Load Laravel config from TOML (e.g., `config/services.toml`)
    $services = Toml::parseFile(config_path('services.toml'));
    config(['services' => $services]);
    
  2. Dynamic Configuration Overrides

    // Merge TOML overrides (e.g., `.env.toml` or user-provided configs)
    $overrides = Toml::parseFile(storage_path('config/overrides.toml'));
    $finalConfig = array_merge_recursive(
        config('default'),
        $overrides
    );
    
  3. CLI Argument Parsing

    // Parse TOML-formatted CLI args (e.g., `--config=deploy.toml`)
    $config = Toml::parse(file_get_contents($argv[1]));
    
  4. Integration with Laravel Service Providers

    public function boot()
    {
        $this->app->singleton('toml-config', function () {
            return Toml::parseFile(config_path('custom.toml'));
        });
    }
    

Best Practices

  • File Caching: Cache parsed TOML files in memory or Redis for performance:
    $cacheKey = 'toml:config';
    $config = cache()->remember($cacheKey, now()->addHours(1), function () {
        return Toml::parseFile(config_path('app.toml'));
    });
    
  • Type Casting: Manually cast values post-parsing (TOML returns strings for numbers/booleans):
    $data['port'] = (int) $data['port'];
    $data['enabled'] = (bool) $data['enabled'];
    
  • Validation: Use Laravel’s Validator to enforce TOML schema rules:
    $validator = Validator::make($data, [
        'database.host' => 'required|string',
        'database.port' => 'required|integer|between:1,65535',
    ]);
    

Gotchas and Tips

Pitfalls

  1. String vs. Number/Boolean Parsing

    • TOML returns all values as strings. Cast explicitly:
      // ❌ Fails silently (returns "123" instead of 123)
      $port = $toml['port'];
      
      // ✅ Correct
      $port = (int) $toml['port'];
      
  2. Date/Time Handling

    • Dates (e.g., 1979-05-27T07:32:00Z) are parsed as strings. Use Carbon:
      use Carbon\Carbon;
      $date = Carbon::parse($toml['date']);
      
  3. Inline Tables vs. Arrays

    • Confusing syntax for beginners:
      # Inline table (parsed as associative array)
      key = { nested = "value" }
      
      # Array (parsed as indexed array)
      key = [1, 2, 3]
      
  4. File Encoding

    • TOML files must be UTF-8. Non-UTF-8 files (e.g., saved as ANSI) will fail silently or corrupt.
  5. Deprecated Methods

    • Avoid Toml::load() (deprecated in favor of parseFile()).

Debugging Tips

  1. Validate Before Parsing

    if (!Toml::validate($tomlContent)) {
        throw new \RuntimeException('Invalid TOML: ' . Toml::getLastError());
    }
    
  2. Inspect Raw Output Use print_r() or var_export() to debug parsed structures:

    var_export(Toml::parse($toml));
    
  3. Test Edge Cases

    • Empty files ({}).
    • Nested arrays/tables.
    • Special values (true, false, null, +/inf, -/nan).

Extension Points

  1. Custom Parsers Extend the parser for domain-specific TOML (e.g., add Laravel-specific defaults):

    class LaravelToml extends Toml
    {
        public static function parseLaravel($toml)
        {
            $data = parent::parse($toml);
            $data['app']['env'] = env('APP_ENV', 'production');
            return $data;
        }
    }
    
  2. TOML Dump Support Use spatie/fork or league/config for dumping PHP arrays back to TOML (this package is read-only).

  3. Integration with Laravel Filesystem Combine with Illuminate/Filesystem for dynamic TOML loading:

    $toml = Storage::disk('config')->get('settings.toml');
    $config = Toml::parse($toml);
    
  4. Schema Validation Pair with webonyx/graphql-php or spatie/laravel-validation-extensions for TOML schema validation.


Config Quirks

  • No Config File: This package has no .toml or .env-style config. All settings are parsed at runtime.
  • Case Sensitivity: TOML keys are case-sensitive (e.g., Databasedatabase).
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor