PHPackages                             mischasigtermans/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. mischasigtermans/laravel-toon

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

mischasigtermans/laravel-toon
=============================

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

v1.1.0(4mo ago)14648.4k↓14.1%6[1 issues](https://github.com/mischasigtermans/laravel-toon/issues)[1 PRs](https://github.com/mischasigtermans/laravel-toon/pulls)MITPHPPHP ^8.2CI passing

Since Dec 7Pushed 4mo ago1 watchersCompare

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

READMEChangelog (6)Dependencies (12)Versions (10)Used By (0)

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

[](#laravel-toon)

[![Latest Version on Packagist](https://camo.githubusercontent.com/e4f2619a07429776203fa90d81219c5878f5a3a59142b10256e9f3bcd4d2f5ce/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d69736368617369677465726d616e732f6c61726176656c2d746f6f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mischasigtermans/laravel-toon)[![Total Downloads](https://camo.githubusercontent.com/3307d21acacd2b05c8736aecdd8aee61407ab0da5e237f3533d51cbb81cf2613/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d69736368617369677465726d616e732f6c61726176656c2d746f6f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mischasigtermans/laravel-toon)

The most complete [TOON](https://toonformat.dev/) implementation for Laravel, and the only one with full [TOON v3.0 specification](https://github.com/toon-format/spec/blob/main/SPEC.md) compliance. Listed as [official Laravel implementation](https://toonformat.dev/ecosystem/implementations.html).

TOON (Token-Optimized Object Notation) is a compact, YAML-like format designed to reduce token usage when sending data to LLMs. This package achieves **~50% token reduction** compared to JSON while maintaining full round-trip fidelity, backed by 470 tests.

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

[](#installation)

```
composer require mischasigtermans/laravel-toon
```

Quick Start
-----------

[](#quick-start)

```
use MischaSigtermans\Toon\Facades\Toon;

$data = [
    'users' => [
        ['id' => 1, 'name' => 'Alice', 'active' => true],
        ['id' => 2, 'name' => 'Bob', 'active' => false],
    ],
];

// Encode to TOON
$toon = Toon::encode($data);

// Decode back to array
$original = Toon::decode($toon);
```

**Output:**

```
users[2]{id,name,active}:
  1,Alice,true
  2,Bob,false

```

### Global Helper Functions

[](#global-helper-functions)

For convenience, global helper functions are available:

```
// Encode to TOON
$toon = toon_encode($data);

// Decode back to array
$original = toon_decode($toon);
```

### Collection Macro: `toToon`

[](#collection-macro-totoon)

You can convert any Laravel collection directly to TOON format with the built-in `toToon` macro:

```
$collection = collect([
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
]);
$toon = $collection->toToon();
```

**Output:**

```
items[2]{id,name}:
  1,Alice
  2,Bob

```

### Eloquent Model: `toToon`

[](#eloquent-model-totoon)

Eloquent models have a `toToon` method, similar to `toJson` and `toArray`:

```
$user = User::find(1);
$toon = $user->toToon();
```

Why TOON?
---------

[](#why-toon)

When building MCP servers or LLM-powered applications, every token counts. JSON's verbosity wastes context window space with repeated keys and structural characters.

**JSON (201 bytes):**

```
{"users":[{"id":1,"name":"Alice","role":"admin"},{"id":2,"name":"Bob","role":"user"},{"id":3,"name":"Carol","role":"user"}]}
```

**TOON (62 bytes) - 69% smaller:**

```
users[3]{id,name,role}:
  1,Alice,admin
  2,Bob,user
  3,Carol,user

```

Benchmarks
----------

[](#benchmarks)

For a typical paginated API response (50 records):

- **JSON**: ~7,597 tokens
- **TOON**: ~3,586 tokens
- **Saved**: ~4,000 tokens per request

Real-world benchmarks from a production application with 17,000+ records:

Data TypeJSONTOONSavings50 records30,389 bytes14,343 bytes**53%**100 records60,856 bytes28,498 bytes**53%**500 records303,549 bytes140,154 bytes**54%**1,000 records604,408 bytes277,614 bytes**54%**Features
--------

[](#features)

### Tabular Format

[](#tabular-format)

Arrays of uniform objects with primitive values are encoded as compact tables:

```
$data = [
    ['id' => 1, 'name' => 'Alice', 'role' => 'admin'],
    ['id' => 2, 'name' => 'Bob', 'role' => 'user'],
];

$toon = Toon::encode($data);
// [2]{id,name,role}:
//   1,Alice,admin
//   2,Bob,user
```

### List Format for Nested Objects

[](#list-format-for-nested-objects)

Arrays containing objects with nested properties use list format for clarity:

```
$data = [
    ['id' => 1, 'author' => ['name' => 'Jane', 'email' => 'jane@example.com']],
    ['id' => 2, 'author' => ['name' => 'John', 'email' => 'john@example.com']],
];

$toon = Toon::encode($data);
// [2]:
//   - id: 1
//     author:
//       name: Jane
//       email: jane@example.com
//   - id: 2
//     author:
//       name: John
//       email: john@example.com

$decoded = Toon::decode($toon);
// Returns original nested structure
```

### Type Preservation

[](#type-preservation)

All scalar types are preserved through encode/decode:

```
$data = [
    'count' => 42,
    'price' => 19.99,
    'active' => true,
    'deleted' => false,
    'notes' => null,
];

$decoded = Toon::decode(Toon::encode($data));
// Types are preserved: int, float, bool, null
```

### String Quoting (Spec-Compliant)

[](#string-quoting-spec-compliant)

Strings containing special characters are automatically quoted per the TOON spec:

```
$data = ['message' => 'Hello, World: How are you?'];
$toon = Toon::encode($data);
// message: "Hello, World: How are you?"

$data = ['text' => "Line 1\nLine 2"];
$toon = Toon::encode($data);
// text: "Line 1\nLine 2"
```

Safe strings (alphanumeric, underscores, dots) remain unquoted for minimal overhead.

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

[](#configuration)

Publish the config file:

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

### Basic Options

[](#basic-options)

```
// config/toon.php
return [
    // Arrays with fewer items use regular object format instead of tables
    'min_rows_for_table' => 2,

    // Delimiter for array values: ',' (default), '\t' (tab), or '|' (pipe)
    'delimiter' => ',',

    // Strict mode for decoding (throws on malformed input)
    'strict' => true,
];
```

### Token-Saving Options

[](#token-saving-options)

```
return [
    // Omit values to save tokens: 'null', 'empty', 'false', or 'all'
    'omit' => ['null', 'empty'],

    // Always skip these keys
    'omit_keys' => ['created_at', 'updated_at'],

    // Shorten verbose keys
    'key_aliases' => [
        'description' => 'desc',
        'organization_id' => 'org_id',
    ],
];
```

### Value Transformation

[](#value-transformation)

```
return [
    // Format dates (DateTime objects and ISO strings)
    'date_format' => 'Y-m-d',

    // Truncate long strings (adds ... suffix)
    'truncate_strings' => 100,

    // Limit decimal places for floats
    'number_precision' => 2,
];
```

Utility Methods
---------------

[](#utility-methods)

### Measure Savings

[](#measure-savings)

```
$data = User::with('roles')->get()->toArray();

$diff = Toon::diff($data);
// [
//     'json_chars' => 12500,
//     'toon_chars' => 5200,
//     'saved_chars' => 7300,
//     'savings_percent' => 58.4,
// ]
```

### Encode Specific Keys Only

[](#encode-specific-keys-only)

```
$users = User::all()->toArray();

// Only include id and name, exclude email, password, etc.
$toon = Toon::only($users, ['id', 'name']);
```

Use Cases
---------

[](#use-cases)

### MCP Servers

[](#mcp-servers)

Reduce token usage when returning data from MCP tool calls:

```
public function handle(): string
{
    $users = User::with('roles')->limit(100)->get();

    return Toon::encode([
        'count' => $users->count(),
        'users' => $users->toArray(),
    ]);
}
```

### LLM Context

[](#llm-context)

Pack more data into your context window:

```
$context = Toon::encode([
    'conversation' => $messages,
    'user_profile' => $user->toArray(),
    'recent_orders' => $orders->toArray(),
]);

$response = $llm->chat([
    ['role' => 'system', 'content' => "Context:\n{$context}"],
    ['role' => 'user', 'content' => $question],
]);
```

### API Responses

[](#api-responses)

Optional TOON responses for token-conscious clients:

```
public function index(Request $request)
{
    $data = Product::paginate()->toArray();

    if ($request->header('Accept') === 'application/toon') {
        return response(Toon::encode($data))
            ->header('Content-Type', 'application/toon');
    }

    return response()->json($data);
}
```

Spec Compliance
---------------

[](#spec-compliance)

This package implements the [TOON v3.0 specification](https://github.com/toon-format/spec/blob/main/SPEC.md) and passes the official specification test suite. Key compliance features:

- **String quoting**: Safe strings unquoted, special characters properly escaped (`\n`, `\r`, `\t`, `\"`, `\\`)
- **Delimiter support**: Comma (default), tab, and pipe delimiters
- **Tabular format**: Compact tables for arrays of primitive-only objects (`[N]{fields}:`)
- **List format**: Readable structure for arrays with nested objects (`[N]:` with `- field:` items)
- **Inline arrays**: Primitive arrays on single line (`key[N]: a,b,c`)
- **Strict mode**: Optional validation during decoding
- **Backward compatibility**: Decoder accepts legacy formats (backslash escaping, dot-notation columns)

Testing
-------

[](#testing)

```
composer test
```

The test suite includes 470 tests covering encoding, decoding, nested object handling, and official spec compliance fixtures.

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

[](#requirements)

- PHP 8.2+
- Laravel 10, 11, or 12

Credits
-------

[](#credits)

- [Mischa Sigtermans](https://github.com/mischasigtermans)

License
-------

[](#license)

MIT

###  Health Score

51

—

FairBetter than 95% of packages

Maintenance73

Regular maintenance activity

Popularity47

Moderate usage in the ecosystem

Community13

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 79.1% 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 ~21 days

Recently: every ~26 days

Total

6

Last Release

149d ago

Major Versions

v0.2.2 → v1.0.02026-01-20

### Community

Maintainers

![](https://www.gravatar.com/avatar/a002abdc851a76410e86443f04058710f9d32f82f31873f8c6544d2e881e79c6?d=identicon)[mischasigtermans](/maintainers/mischasigtermans)

---

Top Contributors

[![mischasigtermans](https://avatars.githubusercontent.com/u/22501510?v=4)](https://github.com/mischasigtermans "mischasigtermans (34 commits)")[![jimmypuckett](https://avatars.githubusercontent.com/u/3220069?v=4)](https://github.com/jimmypuckett "jimmypuckett (5 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (4 commits)")

---

Tags

aijson-alternativelaravelllmmcptoken-optimizationtoken-optimizertoonlaravelmcpaillmtoontoken-optimizationjson-alternative

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[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).

6665.2k](/packages/sbsaga-toon)[laravel/ai

The official AI SDK for Laravel.

1.1k4.6M327](/packages/laravel-ai)[neuron-core/neuron-laravel

Official Neuron AI Laravel SDK.

11747.5k1](/packages/neuron-core-neuron-laravel)

PHPackages © 2026

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