PHPackages                             sulimanbenhalim/laravel-superjson - 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. sulimanbenhalim/laravel-superjson

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

sulimanbenhalim/laravel-superjson
=================================

SuperJSON format for Laravel - preserve JavaScript types in JSON (Beta: CSRF limitations)

0.9.1-beta(8mo ago)01MITPHPPHP ^8.2CI passing

Since Aug 19Pushed 5mo agoCompare

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

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

Laravel SuperJSON
=================

[](#laravel-superjson)

[![GitHub License](https://camo.githubusercontent.com/76c062f5c817b7aa4a6a79652ab64acd51a340805fcf6fe1f3f8b932e4e366f7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f73756c696d616e62656e68616c696d2f6c61726176656c2d73757065726a736f6e)](https://github.com/sulimanbenhalim/laravel-superjson/blob/main/LICENSE.md)[![PHP Version Support](https://camo.githubusercontent.com/2a38189ebddcd255237b8da46df2e1435923035f259b9e4b261fd98ad4e9cea2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344253230382e322d626c7565)](https://www.php.net/supported-versions.php)[![Laravel Version Support](https://camo.githubusercontent.com/1bc65cbe3b5a8d0fa3c453b8f066ce33d867c978dcab5342b4d1bb3a9358f1a6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d25334525334425323031312e302d726564)](https://laravel.com/docs/11.x/releases)[![Beta Version](https://camo.githubusercontent.com/f165840b0b13ca742cb88e6b78873bcaea18cfb343d8e8ec7476bd29a64de714/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7374617475732d626574612d6f72616e6765)](https://github.com/sulimanbenhalim/laravel-superjson)

> Type-preserving JSON serialization for Laravel APIs and JavaScript

**⚠️ BETA VERSION**: This package has known limitations with CSRF-protected POST requests. See [CSRF\_LIMITATION.md](CSRF_LIMITATION.md) for details. Use API routes for POST requests.

Install
-------

[](#install)

```
composer require sulimanbenhalim/laravel-superjson
```

Usage
-----

[](#usage)

### Response Macros

[](#response-macros)

```
// Type-preserving API responses
return response()->superjson([
    'user' => $user,
    'created_at' => now(),
    'big_id' => new BigInt('12345678901234567890'),
    'tags' => new SuperSet(['php', 'laravel']),
]);

// Short alias
return response()->sjson($data);
```

### Request Helpers

[](#request-helpers)

```
// Parse SuperJSON from incoming requests
$data = request()->superjson();
$user = request()->superjson('user.name');

// Short alias
$data = request()->sjson();
```

### Blade Directives

[](#blade-directives)

```

    const data = @superjson($serverData);
    // JavaScript types preserved: Date, BigInt, Set, Map, etc.

```

### Middleware

[](#middleware)

```
// routes/api.php
Route::middleware(['superjson'])->group(function () {
    Route::get('/users', UserController::class);
    Route::post('/users', UserController::class);
});
```

Type Support
------------

[](#type-support)

PHP TypeJavaScript TypeImplementationDateTime, CarbonDateBuilt-inBigInt classBigIntBuilt-inSuperSet classSetBuilt-inSuperMap classMapBuilt-inSerializableUrl classURLBuilt-inSerializableRegex classRegExpBuilt-inException, ThrowableErrorBuilt-inPOST Requests
-------------

[](#post-requests)

**Web routes with CSRF protection have limitations.** See [CSRF\_LIMITATION.md](CSRF_LIMITATION.md) for details.

**Recommended approach for POST requests:**

```
// Use API routes (no CSRF protection)
Route::post('/api/data', function() {
    $data = request()->superjson();
    return response()->superjson($result);
});
```

JavaScript Integration
----------------------

[](#javascript-integration)

Install the [SuperJSON](https://github.com/flightcontrolhq/superjson) JavaScript library:

```
npm install superjson
```

```
import SuperJSON from 'superjson';

// Receiving data (always works)
const response = await fetch('/api/users');
const data = SuperJSON.parse(await response.text());
// data.created_at is a Date object

// Sending data (use API routes)
const payload = {
    timestamp: new Date(),
    bigNumber: BigInt('999999999999999999'),
    tags: new Set(['frontend', 'api'])
};

await fetch('/api/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/superjson',
        'Accept': 'application/superjson'
    },
    body: SuperJSON.stringify(payload)
});
```

Data Types Usage
----------------

[](#data-types-usage)

### BigInt

[](#bigint)

```
use SulimanBenhalim\LaravelSuperJson\DataTypes\BigInt;

$bigNumber = new BigInt('12345678901234567890');
$bigNumber->toString(); // "12345678901234567890"
$bigNumber->toInt();    // Converts to int if safe
```

### Collections

[](#collections)

```
use SulimanBenhalim\LaravelSuperJson\DataTypes\{SuperSet, SuperMap};

// Sets (unique values)
$tags = new SuperSet(['php', 'laravel', 'php']); // 'php' appears once
$tags->add('javascript');
$tags->has('php');     // true
$tags->remove('php');

// Maps (key-value pairs with any key type)
$config = new SuperMap([
    ['theme', 'dark'],
    ['timeout', 300],
    [123, 'numeric key']
]);
$config->set('theme', 'light');
$theme = $config->get('theme'); // 'light'
```

### URLs and RegExp

[](#urls-and-regexp)

```
use SulimanBenhalim\LaravelSuperJson\DataTypes\{SerializableUrl, SerializableRegex};

$url = new SerializableUrl('https://example.com/path?q=search');
$url->getUrl();    // Returns parsed URL components

$pattern = new SerializableRegex('/user-(\d+)/', 'gi');
$pattern->getPattern(); // '/user-(\d+)/'
$pattern->getFlags();   // 'gi'
```

Custom Transformers
-------------------

[](#custom-transformers)

```
use SulimanBenhalim\LaravelSuperJson\Transformers\TypeTransformer;

class MoneyTransformer implements TypeTransformer
{
    public function canTransform($value): bool
    {
        return $value instanceof Money;
    }

    public function transform($value): array
    {
        return [
            'amount' => $value->getAmount(),
            'currency' => $value->getCurrency(),
        ];
    }

    public function restore($value): Money
    {
        return new Money($value['amount'], $value['currency']);
    }

    public function getType(): string
    {
        return 'Money';
    }
}

// Register in service provider
app('superjson')->registerTransformer(new MoneyTransformer());
```

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

[](#configuration)

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

**All Settings**```
// config/superjson.php
return [
    'transformers' => [
        // Custom transformer classes
    ],

    'options' => [
        'preserve_zero_fraction' => true,
        'unescaped_unicode' => true,
        'throw_on_error' => true,
        'max_depth' => 512,
    ],

    'auto_routes' => [
        'api/*',        // Auto-apply to API routes
        'superjson/*',  // Custom route patterns
    ],

    'type_mappings' => [
        DateTime::class => 'Date',
        DateTimeImmutable::class => 'Date',
        'Carbon\Carbon' => 'Date',
    ],

    'security' => [
        'allow_class_restoration' => false,
        'allowed_classes' => [],
        'max_array_size' => 10000,
    ],
];
```

SettingDefaultDescription`transformers`Built-in typesAdditional transformer classes`preserve_zero_fraction``true`Keep .0 in numbers`unescaped_unicode``true`Unicode handling`throw_on_error``true`Error handling behavior`max_depth``512`Nesting limit`auto_routes``['api/*']`Routes for automatic middleware`allow_class_restoration``false`Security: prevent class instantiation`max_array_size``10000`Array size limitTesting
-------

[](#testing)

```
composer test
```

Laravel Version Compatibility
-----------------------------

[](#laravel-version-compatibility)

Laravel VersionPackage Version11.x0.9.x-beta12.x0.9.x-beta**Note**: Version 1.0 will be released once CSRF limitations are resolved.

Security
--------

[](#security)

If you discover any security issues, please email  instead of using the issue tracker.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance66

Regular maintenance activity

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

 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

Every ~2 days

Total

2

Last Release

263d ago

### Community

Maintainers

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

---

Top Contributors

[![sulimanbenhalim](https://avatars.githubusercontent.com/u/44615499?v=4)](https://github.com/sulimanbenhalim "sulimanbenhalim (3 commits)")

---

Tags

jsonlaravelserializationtypessuperjson

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sulimanbenhalim-laravel-superjson/health.svg)

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

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

6115.6k](/packages/sbsaga-toon)[json-mapper/laravel-package

The JsonMapper package for Laravel

25170.4k3](/packages/json-mapper-laravel-package)[laragear/json

Easily retrieve and manipulate `Json` across your application.

363.5k](/packages/laragear-json)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

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

PHPackages © 2026

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