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

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

squareetlabs/laravel-toon
=========================

LaravelToon - Token-Optimized Object Notation for Laravel. Compress AI prompts, reduce API costs, and optimize LLM contexts seamlessly. Perfect for ChatGPT, Claude, Gemini, and OpenAI integrations.

v1.0.0(4mo ago)051↓100%MITPHPPHP &gt;=8.1

Since Nov 14Pushed 1mo agoCompare

[ Source](https://github.com/squareetlabs/LaravelToon)[ Packagist](https://packagist.org/packages/squareetlabs/laravel-toon)[ RSS](/packages/squareetlabs-laravel-toon/feed)WikiDiscussions main Synced today

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

LaravelToon
===========

[](#laraveltoon)

**Token-Optimized Object Notation for Laravel** Compress your AI prompts, reduce API costs, and optimize LLM contexts seamlessly.

[![Quality Score](https://camo.githubusercontent.com/08b23f1c40c5dcd49d6d28d4a0f9d9e75acb95730bdb7a6f6a5564cbb671786f/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f73717561726565746c6162732f4c61726176656c546f6f6e2f6261646765732f7175616c6974792d73636f72652e706e673f623d6d61696e)](https://scrutinizer-ci.com/g/squareetlabs/LaravelToon/)[![Build Status](https://camo.githubusercontent.com/859bcf171f2017ed0bc69ef0537eb5b06edd98f462179a60d283e0888b8084eb/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f73717561726565746c6162732f4c61726176656c546f6f6e2f6261646765732f6275696c642e706e673f623d6d61696e)](https://scrutinizer-ci.com/g/squareetlabs/LaravelToon/)[![Code Intelligence](https://camo.githubusercontent.com/2a45092e6b13be8107328b498117d3895e5d5e50b26e50d04629370b5047c608/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f73717561726565746c6162732f4c61726176656c546f6f6e2f6261646765732f636f64652d696e74656c6c6967656e63652e7376673f623d6d61696e)](https://scrutinizer-ci.com/g/squareetlabs/LaravelToon/)[![Latest Stable Version](https://camo.githubusercontent.com/34b938a4838868eb6df24cc32ca82eb03685a7b49e174cf1f3e8fc2fc88608ac/68747470733a2f2f706f7365722e707567782e6f72672f73717561726565746c6162732f6c61726176656c2d746f6f6e2f762f737461626c65)](https://packagist.org/packages/squareetlabs/laravel-toon)[![License](https://camo.githubusercontent.com/c8c88caa1df16ba3eeef001ae9267c0843c32ca4b195c25fe92abe08371c1474/68747470733a2f2f706f7365722e707567782e6f72672f73717561726565746c6162732f6c61726176656c2d746f6f6e2f6c6963656e7365)](https://packagist.org/packages/squareetlabs/laravel-toon)

Overview
--------

[](#overview)

**LaravelToon** is a native Laravel package that integrates **TOON (Token-Oriented Object Notation)** a compact and readable format designed to optimize token usage in LLM contexts.

### Why LaravelToon

[](#why-laraveltoon)

- **Cost Savings**: Reduces tokens by 60-70%, saving money on APIs
- **Native Integration**: Service providers, Facades, Artisan commands ready to use
- **Multi-LLM**: Supports OpenAI, Claude, Gemini, Mistral with ready-made adapters
- **Deep Analysis**: Token analysis, compression metrics, cost estimation
- **High Performance**: Integrated benchmarking and caching optimizations
- **Interactive Dashboard**: CLI tool to explore and experiment

---

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

[](#quick-start)

### Installation

[](#installation)

```
composer require squareetlabs/laravel-toon
```

### Configuration (Optional)

[](#configuration-optional)

```
php artisan vendor:publish --provider="Squareetlabs\LaravelToon\LaravelToonServiceProvider" --tag=laravel-toon-config
```

### Basic Usage

[](#basic-usage)

```
use Squareetlabs\LaravelToon\Facades\Toon;

// Convert to TOON
$data = [
    'user' => 'John',
    'email' => 'john@example.com',
    'roles' => ['admin', 'user']
];

$toon = Toon::encode($data);
echo $toon;
// user: John
// email: john@example.com
// roles[2]: admin,user

// Or use helpers
echo toon_readable($data);      // Readable format
echo toon_compact($data);       // Compact format
echo toon_tabular($data);       // Tabular format
```

---

Documentation
-------------

[](#documentation)

### Full Guides

[](#full-guides)

- [Quick Start Guide](./QUICKSTART.md) - Get started in 5 minutes
- [Installation Guide](./INSTALLATION.md) - Detailed setup and configuration
- [Examples](./EXAMPLES.md) - 10+ real-world usage examples
- [README](./README.md) - Complete reference

---

Main Features
-------------

[](#main-features)

### 1. Compression and Conversion

[](#1-compression-and-conversion)

```
// Complete compression analysis
$metrics = Toon::getMetrics($data);
echo "Bytes saved: " . $metrics['bytes_saved'] . "\n";
echo "Tokens saved: " . $metrics['tokens_saved'] . "\n";
echo "Ratio: " . $metrics['compression_ratio'] . "\n";

// Compare with JSON
$comparison = Toon::compareWithJson($data);
```

### 2. Token Analysis

[](#2-token-analysis)

```
use Squareetlabs\LaravelToon\Services\TokenAnalyzer;

$analyzer = app(TokenAnalyzer::class);

// Estimate tokens
$tokens = $analyzer->estimate($content);
$comparison = $analyzer->compareJsonVsToon($data);

// Token budget
$budget = $analyzer->budgetTokens(10000, $data);
// ['max_tokens' => 10000, 'tokens_used' => 2500, 'within_budget' => true]
```

### 3. API Cost Calculation

[](#3-api-cost-calculation)

```
use Squareetlabs\LaravelToon\Services\CostCalculator;

$calculator = app(CostCalculator::class);

// Estimate cost for GPT-4o
$cost = $calculator->estimateCost('gpt-4o', $data, 'input');
// ['tokens' => 2500, 'cost' => 0.0625, 'cost_formatted' => '$0.0625']

// Compare JSON vs TOON cost
$comparison = $calculator->estimateWithJsonComparison('gpt-4o', $data);

// Compare prices across models
$models = $calculator->compareModels($data);
```

### 4. LLM API Adapters

[](#4-llm-api-adapters)

```
use Squareetlabs\LaravelToon\Adapters\OpenAIAdapter;

$openai = new OpenAIAdapter();

// Send compressed message to OpenAI
$response = $openai->sendMessage(
    'Analyze this compressed JSON...',
    'gpt-4o',
    ['temperature' => 0.7]
);

// Chat with compressed messages
$messages = [
    ['role' => 'user', 'content' => 'First message'],
    ['role' => 'assistant', 'content' => 'Response'],
];

$chatResponse = $openai->chat($messages, 'gpt-4o');
```

---

Artisan Commands
----------------

[](#artisan-commands)

### toon:convert

[](#toonconvert)

Converts JSON files to TOON or vice versa.

```
# JSON to TOON
php artisan toon:convert data.json --format=readable

# TOON to JSON (decode)
php artisan toon:convert data.toon --decode --pretty

# Save to file
php artisan toon:convert data.json --output=compressed.toon
```

### toon:analyze

[](#toonanalyze)

Analyzes compression and efficiency.

```
php artisan toon:analyze data.json --verbose
```

Shows:

- JSON vs TOON size
- Estimated tokens
- Reduction percentage
- Recommendations

### toon:benchmark

[](#toonbenchmark)

Runs performance and cost estimation benchmarks.

```
php artisan toon:benchmark data.json --iterations=100 --model=gpt-4o
```

Shows:

- Encoding/decoding time
- Size comparison
- Cost estimation

### toon:dashboard

[](#toondashboard)

Interactive dashboard to explore LaravelToon.

```
php artisan toon:dashboard
```

Allows:

- Convert JSON TOON
- Analyze compression
- Estimate costs
- View model prices

---

� Available Helpers
-------------------

[](#-available-helpers)

```
// Encoding
toon($data)                          // Readable format
toon_compact($data)                  // Compact format
toon_readable($data)                 // Readable format
toon_tabular($data)                  // Tabular format
toon_convert($data, 'compact')       // With specified format

// Decoding
toon_decode($toon)                   // TOON to PHP

// Compression and Metrics
toon_compress($data)                 // Full compression
toon_metrics($data)                  // Detailed metrics
toon_compression_summary($data)      // Summary

// Tokens
toon_estimate_tokens($content)       // Estimate tokens
toon_compare_json_vs_toon($data)     // Compare JSON vs TOON
toon_analyze($content)               // Detailed analysis

// Benchmark
toon_benchmark($data, 100)           // Performance benchmark

// Costs
toon_cost_estimate('gpt-4o', $data)          // Estimate cost
toon_cost_compare_models($data)              // Compare models
toon_cost_with_json_comparison('gpt-4o', $data) // With JSON comparison
toon_budget_analysis('gpt-4o', 100, $data)  // Budget analysis
```

---

Integration with Eloquent Models
--------------------------------

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

```
use Squareetlabs\LaravelToon\Traits\HasToonEncoding;

class User extends Model
{
    use HasToonEncoding;
}

$user = User::first();

// Convert to TOON
echo $user->toToon();                    // Readable format
echo $user->toToonCompact();             // Compact format

// Get metrics
$metrics = $user->getToonMetrics();
$ratio = $user->getToonCompressionRatio();
```

---

Validation
----------

[](#validation)

```
use Squareetlabs\LaravelToon\Rules\ValidToonFormat;

$request->validate([
    'compressed_data' => [new ValidToonFormat()],
]);
```

---

Advanced Configuration
----------------------

[](#advanced-configuration)

The `config/laravel-toon.php` file allows you to configure:

```
return [
    // Encoding options
    'encoding' => [
        'indent' => 2,
        'delimiter' => ',',
        'min_rows_to_tabular' => 2,
    ],

    // Token analysis
    'token_analysis' => [
        'enabled' => true,
        'estimate_method' => 'character_ratio',
        'cache_results' => true,
    ],

    // LLM model prices
    'cost_calculation' => [
        'models' => [
            'gpt-4o' => ['input' => 0.0025, 'output' => 0.010],
            'claude-3-sonnet' => ['input' => 0.003, 'output' => 0.015],
            // ... more models
        ],
    ],

    // Compression middleware
    'middleware' => [
        'auto_compress' => false,
        'min_response_size' => 1024,
    ],
];
```

---

Use Cases
---------

[](#use-cases)

### 1. ChatGPT Prompt Optimization

[](#1-chatgpt-prompt-optimization)

```
$prompt = "Analyze this dataset with millions of records...";
$data = $largeDataset;

$optimized = [
    'system_message' => 'You are an expert data analyst',
    'user_prompt' => $prompt,
    'data' => toon_compact($data),
];

// Save 60% of tokens
$tokens = toon_estimate_tokens(json_encode($optimized));
```

### 2. RAG with Optimized Context

[](#2-rag-with-optimized-context)

```
$contextData = $database->search('query', 1000);

$ragPrompt = [
    'context' => toon_compact($contextData),
    'query' => 'User question',
];

$cost = toon_cost_estimate('gpt-4o', $ragPrompt);
// Significantly reduces costs
```

### 3. Cost Monitoring

[](#3-cost-monitoring)

```
// In your controller
public function sendToAI(Request $request)
{
    $data = $request->validated();

    $budget = toon_budget_analysis('gpt-4o', 100, $data);

    if (!$budget['within_budget']) {
        return response()->json([
            'error' => 'Exceeds token budget'
        ]);
    }

    // Proceed...
}
```

---

Testing
-------

[](#testing)

```
use Squareetlabs\LaravelToon\Facades\Toon;

class ToonTest extends TestCase
{
    public function test_compression_ratio()
    {
        $data = ['users' => range(1, 1000)];
        $ratio = Toon::calculateCompressionRatio($data);

        $this->assertLessThan(0.4, $ratio); // Less than 40%
    }
}
```

---

Environment Variables
---------------------

[](#environment-variables)

```
# LLM APIs
OPENAI_API_KEY=sk-...
OPENAI_API_BASE=https://api.openai.com/v1

ANTHROPIC_API_KEY=sk-ant-...

GEMINI_API_KEY=AIzaSy...

MISTRAL_API_KEY=...

# LaravelToon
LARAVEL_TOON_ENABLED=true
```

---

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

[](#contributing)

Contributions are welcome! Please:

1. Fork the repository
2. Create a branch for your feature (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

---

License
-------

[](#license)

Distributed under the MIT License. See `LICENSE` for more information.

---

About
-----

[](#about)

LaravelToon is developed and maintained by [SquareetLabs](https://squareet.com)

---

Support
-------

[](#support)

For support, create an issue in the repository or contact

---

**LaravelToon v1.0.0 - November 14, 2025**

###  Health Score

38

—

LowBetter than 86% of packages

Maintenance83

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

129d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5f0312df8043f114ad6f9c945a452d4e451bd14cecae570f9772ce937630bce5?d=identicon)[squareetlabs](/maintainers/squareetlabs)

---

Top Contributors

[![jcancig](https://avatars.githubusercontent.com/u/446610?v=4)](https://github.com/jcancig "jcancig (6 commits)")

---

Tags

phpjsonformatterlaravelparserdataaitokenlaravel-packageserializationconverteropenaiGeminiclaudephp8llmanthropicgptChatGptlaravel12laravel11promptmistrallaravel9gpt-4laravel-ailaravel10data-transformerlaravel-chatgptlaravel-openaiai-integrationai-toolsprompt-engineeringtoontoken-optimizertoken-efficientlaravel-geminilaravel-anthropiclaravel-mistralai-promptprompt-optimizationprompt-compressioncontext-optimizercontext-compressiontoken-saverllm-toolsai-developer-toolsdata-formatterdata-compressioncompact-jsonserialization-formatyaml-alternativeobject-notationhuman-readable-formattoon-laravellaravel-toontoken-countergpt-4osquareetlabs

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/squareetlabs-laravel-toon/health.svg)](https://phpackages.com/packages/squareetlabs-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).

589.9k](/packages/sbsaga-toon)[helgesverre/toon

Token-Oriented Object Notation - A compact data format for reducing token consumption when sending structured data to LLMs

11626.5k8](/packages/helgesverre-toon)[vizra/vizra-adk

Vizra Agent Development Kit - A comprehensive Laravel package for building intelligent AI agents.

28621.7k](/packages/vizra-vizra-adk)[rajentrivedi/tokenizer-x

TokenizerX calculates required tokens for given prompt

90199.9k3](/packages/rajentrivedi-tokenizer-x)[claude-php/claude-php-sdk-laravel

Laravel integration for the Claude PHP SDK - Anthropic Claude API

505.5k](/packages/claude-php-claude-php-sdk-laravel)

PHPackages © 2026

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