Installation Add the package via Composer:
composer require jamesmoss/toml
No additional configuration is required—it’s a standalone parser.
First Use Case Parse a TOML string or file:
use Jamesmoss\Toml\Toml;
// Parse a string
$tomlString = <<<TOML
title = "Example"
owner = { name = "John Doe", organization = "Acme Inc" }
TOML;
$parsed = Toml::parse($tomlString);
// Returns: ['title' => 'Example', 'owner' => ['name' => 'John Doe', 'organization' => 'Acme Inc']]
// Parse a file
$parsedFile = Toml::parseFile(__DIR__ . '/config.toml');
Where to Look First
Configuration Files Replace PHP arrays or JSON configs with TOML for better readability:
// config/app.toml
[database]
host = "localhost"
port = 3306
$config = Toml::parseFile(config_path('app.toml'));
DB::setHost($config['database']['host']);
User-Generated Data
Parse TOML from user uploads (e.g., settings.toml):
$userToml = $request->file('settings.toml')->getContent();
$userPrefs = Toml::parse($userToml);
Integration with Laravel Services Use in Service Providers or Commands to load external configs:
// app/Providers/AppServiceProvider.php
public function boot()
{
$this->app->singleton('toml-config', function () {
return Toml::parseFile(storage_path('config/overrides.toml'));
});
}
Validation: Combine with Laravel’s Validator to ensure TOML structure matches expectations:
$rules = [
'database.host' => 'required|string',
'database.port' => 'required|integer|between:1,65535',
];
Validator::make($parsedToml, $rules)->validate();
Caching: Cache parsed TOML files if they’re static:
$cacheKey = 'toml_config_' . md5_file($filePath);
$config = Cache::remember($cacheKey, now()->addHours(1), function () use ($filePath) {
return Toml::parseFile($filePath);
});
Deprecated Package
spatie/toml.No Error Handling
try-catch:
try {
$data = Toml::parse($tomlString);
} catch (\Exception $e) {
Log::error("Invalid TOML: " . $e->getMessage());
return response()->json(['error' => 'Invalid config'], 400);
}
Array of Tables Limitation
[table.array] syntax. Workaround:
[[users]]
name = "Alice"
[[users]]
name = "Bob"
Parse manually or pre-convert to a supported format.Log::debug("Parsing TOML:", ['input' => $tomlString]);
Jamesmoss\Toml\Toml for domain-specific TOML (e.g., add schema validation).$tomlData = Toml::parseFile(config_path('toml_overrides.toml'));
config()->set($tomlData);
How can I help you explore Laravel packages today?