PHPackages                             aminrafiei/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. [API Development](/categories/api)
4. /
5. aminrafiei/laravel-toon

ActiveLibrary[API Development](/categories/api)

aminrafiei/laravel-toon
=======================

TOON (Token-Oriented Object Notation) format support for Laravel

v1.0.0(5mo ago)12MITPHPPHP ^8.1|^8.2|^8.3|^8.4

Since Nov 20Pushed 5mo agoCompare

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

READMEChangelog (1)Dependencies (3)Versions (2)Used By (0)

TOON for Laravel
================

[](#toon-for-laravel)

A Laravel package that lets you return API responses in TOON format instead of JSON. If you're building APIs that talk to LLMs (like GPT or Claude), this can cut your token usage by 30-70%, which means real money saved on API costs.

What's TOON?
------------

[](#whats-toon)

TOON (Token-Oriented Object Notation) is basically a more compact way to represent the same data you'd normally send as JSON. It uses indentation instead of braces, and for arrays of objects, it can use a table-like format that's way more efficient.

Here's the difference:

**JSON** (459 characters):

```
{
  "users": [
    {"id": 1, "name": "Alice", "email": "alice@example.com"},
    {"id": 2, "name": "Bob", "email": "bob@example.com"},
    {"id": 3, "name": "Charlie", "email": "charlie@example.com"}
  ]
}
```

**TOON** (146 characters):

```
users[3]{id,name,email}:
  1,Alice,alice@example.com
  2,Bob,bob@example.com
  3,Charlie,charlie@example.com

```

That's 68% smaller. For a million API calls, that's the difference between spending $500 and $160 on LLM costs.

Why Would I Use This?
---------------------

[](#why-would-i-use-this)

Honestly, if you're just building a regular REST API for a web or mobile app, stick with JSON. Browsers and most HTTP clients expect JSON.

But if you're:

- Sending data to GPT/Claude and paying per token
- Building tools that integrate with LLMs
- Processing large amounts of structured data through AI models
- Trying to fit more context into LLM prompts

Then yeah, TOON can save you a bunch of money and let you send more data in less space.

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

[](#installation)

```
composer require aminrafiei/laravel-toon
```

Usage
-----

[](#usage)

The nice thing is you barely have to change anything. Just extend `ToonResource` instead of `JsonResource`:

```
use Toon\ToonResource;

class UserResource extends ToonResource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }
}
```

That's it. Your `toArray()` method stays exactly the same. All the Laravel Resource features you're used to (conditional attributes, relationships, etc.) still work.

### In Your Controller

[](#in-your-controller)

```
// Single resource
public function show(User $user)
{
    return new UserResource($user);
}

// Collection
public function index()
{
    return UserResource::collection(User::all());
}
```

The response comes out in TOON format with `Content-Type: text/plain; charset=UTF-8`.

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

[](#configuration)

If you want to squeeze out even more efficiency, use tabs instead of commas:

```
class UserResource extends ToonResource
{
    protected string $delimiter = "\t";
}
```

You can also change indentation or enable key folding (which collapses single-key nested objects):

```
class UserResource extends ToonResource
{
    protected int $indentSize = 4;
    protected bool $keyFolding = true;
}
```

Or configure it per-request:

```
return (new UserResource($user))
    ->withDelimiter("\t")
    ->withKeyFolding(true);
```

How It Works
------------

[](#how-it-works)

The encoder looks at your data and picks the most efficient format:

- **Simple values**: `name: John`
- **Nested objects**: Uses indentation
- **Arrays of primitives**: `tags[3]: admin,user,premium`
- **Arrays of objects with same keys**: Table format (super efficient)
- **Mixed arrays**: List format with hyphens

It's all automatic. You don't have to think about it.

Real World Numbers
------------------

[](#real-world-numbers)

I tested this with actual API responses from a Laravel app:

- Simple objects: ~30% smaller
- Nested structures: ~27% smaller
- Collections (the big win): ~68% smaller

That collection savings is where it really matters. If you're returning lists of users, products, whatever - that's where you see the biggest difference.

When NOT to Use This
--------------------

[](#when-not-to-use-this)

Don't use TOON if:

- You're building a public API (stick with JSON for compatibility)
- Your clients are browsers or mobile apps
- You're integrating with third-party services that expect JSON
- You just don't want to deal with a non-standard format

TOON is specifically designed for AI/LLM use cases. For everything else, JSON is probably the better choice.

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

[](#requirements)

- PHP 8.1 or newer
- Laravel 10 or 11

Testing
-------

[](#testing)

```
composer test
```

The Spec
--------

[](#the-spec)

This implements [TOON Format Specification v1.5](https://toonformat.dev/). The format is actually pretty well thought out - check out the spec if you're curious about the details.

Contributing
------------

[](#contributing)

Found a bug? Have an idea? Open an issue or PR on GitHub. I'm pretty responsive.

License
-------

[](#license)

MIT. Do whatever you want with it.

Links
-----

[](#links)

- [TOON Spec](https://toonformat.dev/)
- [Laravel Resources Docs](https://laravel.com/docs/eloquent-resources)

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance71

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Unknown

Total

1

Last Release

173d ago

### Community

Maintainers

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

---

Top Contributors

[![aminrafiei](https://avatars.githubusercontent.com/u/25347159?v=4)](https://github.com/aminrafiei "aminrafiei (1 commits)")

---

Tags

apilaravelresourcestoontoken-efficientdata-format

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[resend/resend-laravel

Resend for Laravel

1191.4M6](/packages/resend-resend-laravel)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)[surface/laravel-webfinger

A Laravel package to create an ActivityPub webfinger.

113.8k](/packages/surface-laravel-webfinger)

PHPackages © 2026

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