sulimanbenhalim/laravel-superjson
Composer 安装命令:
composer require sulimanbenhalim/laravel-superjson
包简介
SuperJSON format for Laravel - preserve JavaScript types in JSON (Beta: CSRF limitations)
README 文档
README
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 for details. Use API routes for POST requests.
Install
composer require sulimanbenhalim/laravel-superjson
Usage
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
// Parse SuperJSON from incoming requests $data = request()->superjson(); $user = request()->superjson('user.name'); // Short alias $data = request()->sjson();
Blade Directives
<script> const data = @superjson($serverData); // JavaScript types preserved: Date, BigInt, Set, Map, etc. </script>
Middleware
// routes/api.php Route::middleware(['superjson'])->group(function () { Route::get('/users', UserController::class); Route::post('/users', UserController::class); });
Type Support
| PHP Type | JavaScript Type | Implementation |
|---|---|---|
| DateTime, Carbon | Date | Built-in |
| BigInt class | BigInt | Built-in |
| SuperSet class | Set | Built-in |
| SuperMap class | Map | Built-in |
| SerializableUrl class | URL | Built-in |
| SerializableRegex class | RegExp | Built-in |
| Exception, Throwable | Error | Built-in |
POST Requests
Web routes with CSRF protection have limitations. See 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
Install the 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
BigInt
use SulimanBenhalim\LaravelSuperJson\DataTypes\BigInt; $bigNumber = new BigInt('12345678901234567890'); $bigNumber->toString(); // "12345678901234567890" $bigNumber->toInt(); // Converts to int if safe
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
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
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
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, ], ];
| Setting | Default | Description |
|---|---|---|
transformers |
Built-in types | Additional 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 limit |
Testing
composer test
Laravel Version Compatibility
| Laravel Version | Package Version |
|---|---|
| 11.x | 0.9.x-beta |
| 12.x | 0.9.x-beta |
Note: Version 1.0 will be released once CSRF limitations are resolved.
Security
If you discover any security issues, please email soliman.benhalim@gmail.com instead of using the issue tracker.
License
The MIT License (MIT). Please see License File for more information.
sulimanbenhalim/laravel-superjson 适用场景与选型建议
sulimanbenhalim/laravel-superjson 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 08 月 19 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「json」 「serialization」 「laravel」 「types」 「superjson」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 sulimanbenhalim/laravel-superjson 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 sulimanbenhalim/laravel-superjson 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 sulimanbenhalim/laravel-superjson 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Fork of jms/serializer 1.14.1 with support for modern PHP versions.
Kinikit - PHP Application development framework MVC component
De/normalize business objects without tightly coupling them to your normalization format
ext-json wrapper with sane defaults
A package to cast json fields, each sub-keys is castable
Runn Me! Serialization Library
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 25
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-08-19