PHPackages                             robertgdev/laravel-toon - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. robertgdev/laravel-toon

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

robertgdev/laravel-toon
=======================

Laravel integration for TOON - A human-readable data serialization format

1.2.0(5mo ago)611MITPHPPHP ^8.2

Since Nov 7Pushed 5mo agoCompare

[ Source](https://github.com/robertgdev/laravel-toon)[ Packagist](https://packagist.org/packages/robertgdev/laravel-toon)[ RSS](/packages/robertgdev-laravel-toon/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (7)Versions (4)Used By (0)

Laravel TOON
============

[](#laravel-toon)

Laravel integration for TOON - A human-readable data serialization format.

This package provides Laravel-specific features on top of the [helgesverre/toon-php](https://github.com/HelgeSverre/toon-php) core library.

Installation
------------

[](#installation)

```
composer require robertgdev/laravel-toon
```

This will automatically install the `helgesverre/toon-php` core library as a dependency.

Configuration
-------------

[](#configuration)

### Publishing Configuration

[](#publishing-configuration)

Publish the configuration file to customize default encoding/decoding options:

```
php artisan vendor:publish --tag=toon-config
```

This creates `config/toon.php` where you can set default options.

### Configuration Options

[](#configuration-options)

The config file supports both file-based configuration and environment variables:

```
// config/toon.php
return [
    'encode' => [
        'indent' => env('TOON_ENCODE_INDENT', 2),
        'delimiter' => env('TOON_ENCODE_DELIMITER', ','),
        'lengthMarker' => env('TOON_ENCODE_LENGTH_MARKER', false),
    ],
    'decode' => [
        'indent' => env('TOON_DECODE_INDENT', 2),
        'strict' => env('TOON_DECODE_STRICT', true),
        'objectsAsStdClass' => env('TOON_DECODE_OBJECTS_AS_STDCLASS', false),
    ],
];
```

### Environment Variables

[](#environment-variables)

Add these to your `.env` file to configure TOON globally:

```
# Encoding options
TOON_ENCODE_INDENT=2
TOON_ENCODE_DELIMITER=,
TOON_ENCODE_LENGTH_MARKER=false

# Decoding options
TOON_DECODE_INDENT=2
TOON_DECODE_STRICT=true
```

**Available Delimiters:**

- `,` (comma, default)
- `\t` (tab - use `"\t"` in config or `\t` in .env)
- `|` (pipe)

**Length Marker:**

- `false` (default) - no marker
- `true` or `#` - adds `#` prefix to array lengths

### Using Configured Defaults

[](#using-configured-defaults)

When you use the facade without options, it automatically uses your configured defaults:

```
use RobertGDev\LaravelToon\Facades\Toon;

// Uses config defaults
$encoded = Toon::encode($data);
$decoded = Toon::decode($encoded);

// Override with custom options
use HelgeSverre\Toon\EncodeOptions;
$encoded = Toon::encode($data, new EncodeOptions(indent: 4));
```

Programmatic Usage
------------------

[](#programmatic-usage)

### Using the Facade (Laravel-style)

[](#using-the-facade-laravel-style)

The package provides a Laravel facade for easy access:

```
use RobertGDev\LaravelToon\Facades\Toon;
use HelgeSverre\Toon\EncodeOptions;

// Simple encoding
$data = ['name' => 'Ada', 'age' => 30, 'active' => true];
$encoded = Toon::encode($data);

// With options
$options = new EncodeOptions(
    indent: 4,
    delimiter: "\t",
    lengthMarker: '#'
);
$encoded = Toon::encode($data, $options);

// Decoding
$decoded = Toon::decode($encoded);
```

The facade is automatically registered via package discovery as `Toon`, so you can also use it without importing:

```
$encoded = \Toon::encode(['key' => 'value']);
$decoded = \Toon::decode($encoded);
```

### Using the Core Library Directly

[](#using-the-core-library-directly)

You can also use the core library directly:

```
use HelgeSverre\Toon\Toon;

$encoded = Toon::encode(['name' => 'Ada']);
$decoded = Toon::decode($encoded);
```

For detailed API documentation, see the [helgesverre/toon](https://github.com/helgesverre/toon) package.

### Using the Toonable Interface and Trait

[](#using-the-toonable-interface-and-trait)

The package provides a convenient way to make your DTOs, models, or any PHP objects directly convertible to TOON format using the `Toonable` interface and `ToonFormat` trait.

#### Basic Usage

[](#basic-usage)

```
use RobertGDev\LaravelToon\Contracts\Toonable;
use RobertGDev\LaravelToon\Concerns\ToonFormat;

class UserDTO implements Toonable
{
    use ToonFormat;

    public function __construct(
        public string $name,
        public int $age,
        public array $roles,
    ) {}
}

// Now you can call toToon() directly on your object
$user = new UserDTO('John Doe', 30, ['admin', 'owner']);
$toon = $user->toToon();

// Output:
// name: John Doe
// age: 30
// roles[2]: admin,owner
```

#### With Custom Encoding Options

[](#with-custom-encoding-options)

You can pass custom encoding options to the `toToon()` method:

```
use HelgeSverre\Toon\EncodeOptions;

$user = new UserDTO('John Doe', 30, ['admin', 'owner']);

// Use a custom delimiter
$options = new EncodeOptions(delimiter: '|');
$toon = $user->toToon($options);

// Output:
// name: John Doe
// age: 30
// roles[2|]: admin|owner
```

#### Using with Eloquent Models

[](#using-with-eloquent-models)

You can also use this with Laravel Eloquent models:

```
use Illuminate\Database\Eloquent\Model;
use RobertGDev\LaravelToon\Contracts\Toonable;
use RobertGDev\LaravelToon\Concerns\ToonFormat;

class User extends Model implements Toonable
{
    use ToonFormat;

    // Your model definition...
}

// Convert a model instance to TOON
$user = User::find(1);
$toon = $user->toToon();
```

Artisan Command
---------------

[](#artisan-command)

The package includes an Artisan command for converting between JSON and TOON formats:

```
# Encode JSON to TOON
php artisan toon:convert input.json --output=output.toon

# Decode TOON to JSON
php artisan toon:convert input.toon --output=output.json

# Auto-detect mode based on file extension
php artisan toon:convert data.json  # Encodes to TOON
php artisan toon:convert data.toon  # Decodes to JSON

# Print to stdout instead of file
php artisan toon:convert input.json

# Use custom delimiter (tab or pipe)
php artisan toon:convert input.json --delimiter="\t"
php artisan toon:convert input.json --delimiter="|"

# Use length marker
php artisan toon:convert input.json --length-marker

# Show token statistics
php artisan toon:convert input.json --stats

# Custom indentation
php artisan toon:convert input.json --indent=4

# Disable strict mode for decoding
php artisan toon:convert input.toon --no-strict
```

### Command Options

[](#command-options)

- `input` - Input file path (required)
- `--o|output` - Output file path (prints to stdout if not specified)
- `--e|encode` - Force encode mode (auto-detected by default)
- `--d|decode` - Force decode mode (auto-detected by default)
- `--delimiter` - Delimiter for arrays: comma (,), tab (\\t), or pipe (|)
- `--indent` - Indentation size (default: 2)
- `--length-marker` - Use length marker (#) for arrays
- `--strict` - Enable strict mode for decoding (default: true)
- `--no-strict` - Disable strict mode for decoding
- `--stats` - Show token statistics

Features
--------

[](#features)

- **Laravel Facade**: Use `Toon::encode()` and `Toon::decode()` anywhere in your Laravel app
- **Toonable Interface &amp; Trait**: Add `toToon()` method to any class (DTOs, models, etc.) with a simple trait
- **Artisan Command**: Convert files between JSON and TOON formats via CLI
- **Auto-Registration**: Service provider and facade automatically registered via package discovery
- **Service Container**: Toon class registered as a singleton in Laravel's container
- **File Operations**: Read and write TOON files with ease
- **Token Statistics**: Estimate token savings when converting to TOON

Package Structure
-----------------

[](#package-structure)

This package is a thin Laravel integration layer. The core TOON functionality is provided by the `helgesverre/toon` package, which is a standalone PHP library.

### What's in this package:

[](#whats-in-this-package)

- [`ToonServiceProvider`](src/ToonServiceProvider.php) - Registers the service and command
- [`Toon` Facade](src/Facades/Toon.php) - Laravel facade for easy access
- [`ToonCommand`](src/Console/ToonCommand.php) - Artisan command for file conversion
- [`Toonable` Interface](src/Contracts/Toonable.php) - Contract for objects convertible to TOON
- [`ToonFormat` Trait](src/Concerns/ToonFormat.php) - Provides `toToon()` method implementation
- Configuration file with Laravel integration
- Comprehensive integration test suite covering all features

### What's in the core package:

[](#whats-in-the-core-package)

- All encoding/decoding logic
- Type definitions and options
- Core TOON parser and serializer

See [helgesverre/toon](https://github.com/helgesverre/toon) for the core library documentation.

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 10.x or 11.x or 12.x
- helgesverre/toon (automatically installed)

Testing
-------

[](#testing)

Run the test suite with:

```
vendor/bin/pest
```

The package includes 38 comprehensive tests covering:

- Artisan command functionality (15 tests)
- Configuration and service provider features (10 tests)
- Laravel integration and facade functionality (13 tests)

License
-------

[](#license)

MIT License

###  Health Score

37

—

LowBetter than 82% of packages

Maintenance75

Regular maintenance activity

Popularity8

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 66.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~7 days

Total

3

Last Release

168d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/657a8663556c9228027378e96e032c628c18686f7a84129c7da4b2428b8ae82f?d=identicon)[robertgdev](/maintainers/robertgdev)

---

Top Contributors

[![WendellAdriel](https://avatars.githubusercontent.com/u/11641518?v=4)](https://github.com/WendellAdriel "WendellAdriel (2 commits)")[![robertgdev](https://avatars.githubusercontent.com/u/343614?v=4)](https://github.com/robertgdev "robertgdev (1 commits)")

###  Code Quality

TestsPest

Static AnalysisPHPStan

### Embed Badge

![Health badge](/badges/robertgdev-laravel-toon/health.svg)

```
[![Health](https://phpackages.com/badges/robertgdev-laravel-toon/health.svg)](https://phpackages.com/packages/robertgdev-laravel-toon)
```

###  Alternatives

[spatie/laravel-sitemap

Create and generate sitemaps with ease

2.6k14.6M107](/packages/spatie-laravel-sitemap)[fumeapp/modeltyper

Generate TypeScript interfaces from Laravel Models

196277.9k](/packages/fumeapp-modeltyper)[rajentrivedi/tokenizer-x

TokenizerX calculates required tokens for given prompt

91214.0k3](/packages/rajentrivedi-tokenizer-x)[ultrono/laravel-sitemap

Sitemap generator for Laravel 11, 12 and 13

36412.6k6](/packages/ultrono-laravel-sitemap)[mischasigtermans/laravel-toon

Token-Optimized Object Notation encoder/decoder for Laravel with intelligent nested object handling

13113.1k](/packages/mischasigtermans-laravel-toon)[sbsaga/toon

🧠 TOON for Laravel — a compact, human-readable, and token-efficient data format for AI prompts &amp; LLM contexts. Perfect for ChatGPT, Gemini, Claude, Mistral, and OpenAI integrations (JSON ⇄ TOON).

6115.6k](/packages/sbsaga-toon)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
