### Install Laravel SuperJSON with Composer
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/README.md
Install the Laravel SuperJSON package using Composer. This command downloads and installs the package into your Laravel project, making its features available for use.
```bash
composer require sulimanbenhalim/laravel-superjson
```
--------------------------------
### Install Laravel SuperJSON Bridge Package
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
This bash command installs the Laravel SuperJSON Bridge package using Composer. This package enables seamless preservation of JavaScript types between Laravel APIs and clients using the SuperJSON format.
```bash
composer require yourvendor/laravel-superjson-bridge
```
--------------------------------
### GitHub Actions Workflow for Tests (tests.yml)
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
Automates the testing process for the package on GitHub. It sets up multiple PHP and Laravel versions, installs dependencies, and executes PHPUnit tests on each push or pull request.
```yaml
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
php: [8.1, 8.2, 8.3]
laravel: [10.*, 11.*]
include:
- laravel: 10.*
testbench: 8.*
- laravel: 11.*
testbench: 9.*
name: P${{ matrix.php }} - L${{ matrix.laravel }}
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring, json, bcmath
coverage: none
- name: Install dependencies
run: |
composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update
composer update --prefer-dist --no-interaction
- name: Execute tests
run: vendor/bin/phpunit
```
--------------------------------
### Create and Manage SuperMap Collections in PHP
Source: https://context7.com/sulimanbenhalim/laravel-superjson/llms.txt
Demonstrates how to create, set, get, delete, and iterate over SuperMap objects, which are compatible with JavaScript Map. This allows for key-value pairs with any data type as keys, suitable for API responses.
```php
use SulimanBenhalim\LaravelSuperJson\DataTypes\SuperMap;
// Create map from entries array
$config = new SuperMap([
['theme', 'dark'],
['timeout', 300],
['debug', true],
[123, 'numeric key'],
]);
// Set values
$config->set('language', 'en');
$config->set('theme', 'light'); // Updates existing
// Get values
$theme = $config->get('theme'); // 'light'
$missing = $config->get('nonexistent'); // null
// Check existence
if ($config->has('timeout')) {
$timeout = $config->get('timeout');
}
// Delete entries
$deleted = $config->delete('debug'); // Returns true if deleted
// Iterate over entries
foreach ($config as [$key, $value]) {
echo "$key => $value";
}
// Get size
$count = count($config); // or $config->count()
// Convert to array
$entries = $config->toArray(); // [[key1, val1], [key2, val2], ...]
// Use in responses - becomes JavaScript Map
return response()->superjson([
'user_preferences' => new SuperMap([
['notifications', true],
['email_frequency', 'daily'],
['theme', 'auto'],
]),
]);
```
--------------------------------
### Implement Custom Type Transformers in PHP
Source: https://context7.com/sulimanbenhalim/laravel-superjson/llms.txt
Provides a guide on creating custom transformers by implementing the TypeTransformer interface in PHP. This allows for the serialization of domain-specific objects, like a 'Money' object, into a structured format for API responses.
```php
use SulimanBenhalim\LaravelSuperJson\Transformers\TypeTransformer;
use SulimanBenhalim\LaravelSuperJson\Facades\SuperJson;
// Define custom transformer
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()->getCode(),
];
}
public function restore($value): Money
{
return new Money(
$value['amount'],
new Currency($value['currency'])
);
}
public function getType(): string
{
return 'Money';
}
}
// Register in service provider
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
SuperJson::registerTransformer(new MoneyTransformer());
}
}
// Use in application
$price = new Money(1999, new Currency('USD'));
return response()->superjson([
'product' => $product,
'price' => $price, // Automatically transformed
'discount' => new Money(500, new Currency('USD')),
]);
```
--------------------------------
### PHP: Serialize and Deserialize Data with Laravel SuperJSON
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
This example demonstrates basic data serialization and deserialization using the SuperJson facade in Laravel. It shows how to serialize an array containing standard PHP types and Laravel's `now()` helper, preserving them as JSON with metadata for types like 'Date'.
```php
'John Doe',
'created_at' => now(),
'updated_at' => now()->addDays(5),
];
$serialized = SuperJson::serialize($data);
// Result:
// [
// 'json' => [
// 'name' => 'John Doe',
// 'created_at' => '2023-10-05T12:00:00+00:00',
// 'updated_at' => '2023-10-10T12:00:00+00:00',
// ],
// 'meta' => [
// 'values' => [
// 'created_at' => ['Date'],
// 'updated_at' => ['Date'],
// ]
// ]
// ]
```
--------------------------------
### JavaScript Client Usage with SuperJSON
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
Explains how to use the SuperJSON JavaScript client package for sending and receiving data with a Laravel backend. It covers installation, importing, stringifying data containing types like `Date` and `BigInt`, and parsing responses while preserving data types.
```javascript
// Install the SuperJSON package
npm install superjson
// Import and use
import SuperJSON from 'superjson';
// Sending to Laravel
const data = {
timestamp: new Date(),
bigNumber: BigInt('99999999999999999999'),
tags: new Set(['js', 'frontend']),
};
const response = await fetch('/api/endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/superjson',
'Accept': 'application/superjson',
},
body: SuperJSON.stringify(data),
});
const result = SuperJSON.parse(await response.text());
// Types are preserved! result.timestamp is a Date object
```
--------------------------------
### Recommended POST Request Handling with API Routes
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/README.md
For POST requests, it is recommended to use API routes without CSRF protection to avoid limitations. This example demonstrates how to handle incoming SuperJSON data and return a SuperJSON response within an API route.
```php
// Use API routes (no CSRF protection)
Route::post('/api/data', function() {
$data = request()->superjson();
return response()->superjson($result);
});
```
--------------------------------
### Integrate SuperJSON for Client-Side Data Handling (JavaScript)
Source: https://context7.com/sulimanbenhalim/laravel-superjson/llms.txt
This JavaScript code demonstrates how to integrate SuperJSON with a frontend application to receive data from a Laravel API and send data to it, preserving data types. It shows examples of parsing API responses to maintain Date, BigInt, Set, and Map types, and stringifying JavaScript objects into SuperJSON format for API requests. It also includes a utility class 'ApiClient' for simplifying API requests with automatic SuperJSON serialization and deserialization.
```javascript
import SuperJSON from 'superjson';
// Receiving data from Laravel API
async function fetchUser(userId) {
const response = await fetch(`/api/users/${userId}`, {
headers: {
'Accept': 'application/superjson',
}
});
const text = await response.text();
const data = SuperJSON.parse(text);
// Types are preserved
console.log(data.created_at instanceof Date); // true
console.log(typeof data.account_id); // 'bigint'
console.log(data.roles instanceof Set); // true
return data;
}
// Sending data to Laravel API
async function createEvent(eventData) {
const payload = {
name: 'Conference 2024',
start_date: new Date('2024-12-01'),
end_date: new Date('2024-12-03'),
max_attendees: BigInt('999999999'),
categories: new Set(['tech', 'business']),
metadata: new Map([
['venue', 'Convention Center'],
['capacity', 5000]
])
};
const response = await fetch('/api/events', {
method: 'POST',
headers: {
'Content-Type': 'application/superjson',
'Accept': 'application/superjson',
},
body: SuperJSON.stringify(payload)
});
const result = SuperJSON.parse(await response.text());
return result;
}
// Using with fetch wrapper
class ApiClient {
async request(url, options = {}) {
const response = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/superjson',
'Accept': 'application/superjson',
...options.headers,
},
body: options.body ? SuperJSON.stringify(options.body) : undefined,
});
if (!response.ok) {
const error = SuperJSON.parse(await response.text());
throw error; // JavaScript Error object
}
return SuperJSON.parse(await response.text());
}
}
const api = new ApiClient();
const user = await api.request('/api/users/1');
```
--------------------------------
### Implement Custom Type Transformers in Laravel
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
Provides an example of creating and registering a custom type transformer for SuperJSON in a Laravel application. This allows the package to serialize and deserialize custom PHP objects, such as a `Money` class, by defining `canTransform`, `transform`, `restore`, and `getType` methods.
```php
use YourVendor\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 a service provider
app('superjson')->registerTransformer(new MoneyTransformer());
```
--------------------------------
### Run Package Tests
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/README.md
This bash command executes the test suite for the Laravel SuperJSON package. Running tests is crucial to ensure the package is functioning as expected and to verify any modifications or upgrades.
```bash
composer test
```
--------------------------------
### Create and Use SerializableRegex Objects in PHP
Source: https://context7.com/sulimanbenhalim/laravel-superjson/llms.txt
Illustrates the creation and usage of SerializableRegex objects in PHP, which are converted to JavaScript RegExp objects in API responses. This enables pattern matching with predefined regular expressions.
```php
use SulimanBenhalim\LaravelSuperJson\DataTypes\SerializableRegex;
// Create regex with pattern and flags
$emailPattern = new SerializableRegex('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}', 'i');
$phonePattern = new SerializableRegex('^\+?[1-9]\d{1,14}$', 'g');
$urlPattern = new SerializableRegex('https?:\/\/(www\.)?[-a-z0-9@:%._\+~#=]{1,256}\.[a-z]{2,6}\b', 'gi');
// Get components
$pattern = $emailPattern->getPattern(); // '[a-z0-9._%+-]+@...'
$flags = $emailPattern->getFlags(); // 'i'
// Use in API responses - becomes JavaScript RegExp
return response()->superjson([
'validation_rules' => [
'email' => $emailPattern,
'phone' => $phonePattern,
'website' => $urlPattern,
],
]);
```
--------------------------------
### Create Laravel SuperJSON Bridge Package Directory Structure
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
This bash script defines the standard directory structure for a Laravel package, including configuration, source code, tests, and GitHub workflow files. It follows Laravel conventions for discoverability and maintainability.
```bash
laravel-superjson-bridge/
├── composer.json
├── README.md
├── LICENSE.md
├── .gitignore
├── phpunit.xml
├── src/
│ ├── SuperJsonServiceProvider.php
│ ├── SuperJson.php
│ ├── Transformers/
│ │ ├── TypeTransformer.php
│ │ ├── DateTransformer.php
│ │ ├── BigIntTransformer.php
│ │ └── CollectionTransformer.php
│ ├── Http/
│ │ └── Middleware/
│ │ └── HandleSuperJsonRequests.php
│ ├── Facades/
│ │ └── SuperJson.php
│ └── Exceptions/
│ └── SuperJsonException.php
├── config/
│ └── superjson.php
├── tests/
│ ├── TestCase.php
│ ├── Unit/
│ └── Feature/
└── .github/
└── workflows/
└── tests.yml
```
--------------------------------
### PHPUnit Configuration (phpunit.xml)
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
Configures PHPUnit for testing the Laravel package. It sets up test suites for Unit and Feature tests, includes coverage for the 'src' directory, and defines environment variables for testing.
```xml
./tests/Unit
./tests/Feature
./src
```
--------------------------------
### Create and Use SerializableUrl Objects in PHP
Source: https://context7.com/sulimanbenhalim/laravel-superjson/llms.txt
Shows how to create SerializableUrl objects for structured URL handling in PHP. These objects are transformed into JavaScript URL objects in API responses, providing easy access to URL components.
```php
use SulimanBenhalim\LaravelSuperJson\DataTypes\SerializableUrl;
// Create URL object
$apiUrl = new SerializableUrl('https://api.example.com/v1/users?page=1&limit=50');
$websiteUrl = new SerializableUrl('https://example.com/path?query=value#section');
// Get parsed components
$components = $apiUrl->getUrl();
// Returns array with protocol, host, path, query, hash, etc.
// Use in API responses - becomes JavaScript URL object
return response()->superjson([
'api_endpoint' => $apiUrl,
'documentation_url' => new SerializableUrl('https://docs.example.com'),
'callback_url' => new SerializableUrl($request->input('callback')),
]);
```
--------------------------------
### Publish SuperJSON Configuration File
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/README.md
This bash command publishes the SuperJSON configuration file to your Laravel project. This allows you to customize various aspects of the package's behavior, such as transformers, serialization options, security settings, and route configurations.
```bash
php artisan vendor:publish --tag=superjson-config
```
--------------------------------
### Laravel SuperJSON Configuration File
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
Presents the structure of the `config/superjson.php` configuration file for Laravel. It details options for custom transformers, serialization settings like `preserve_zero_fraction` and `unescaped_unicode`, automatic route application, and security settings for class restoration.
```php
// config/superjson.php
return [
'transformers' => [
// Add custom transformers
\App\Transformers\MyCustomTransformer::class,
],
'options' => [
'preserve_zero_fraction' => true,
'unescaped_unicode' => true,
'throw_on_error' => true,
'max_depth' => 512,
],
'auto_routes' => [
'api/*', // Auto-apply to all API routes
],
'security' => [
'allow_class_restoration' => false,
'allowed_classes' => [],
],
];
```
--------------------------------
### Configure Composer for Laravel SuperJSON Bridge Package
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
This JSON configuration file sets up the `composer.json` for the `laravel-superjson-bridge` package. It defines package metadata, dependencies (both production and development), autoloading rules, Laravel service provider and facade registration, and script commands for testing and analysis.
```json
{
"name": "yourvendor/laravel-superjson-bridge",
"description": "SuperJSON format bridge for Laravel - preserve JavaScript types in JSON",
"keywords": ["laravel", "superjson", "json", "serialization", "types"],
"license": "MIT",
"authors": [
{
"name": "Your Name",
"email": "your@email.com"
}
],
"require": {
"php": "^8.1",
"illuminate/support": "^10.0|^11.0",
"illuminate/http": "^10.0|^11.0"
},
"require-dev": {
"orchestra/testbench": "^8.0|^9.0",
"phpunit/phpunit": "^10.0",
"phpstan/phpstan": "^1.10"
},
"autoload": {
"psr-4": {
"YourVendor\\LaravelSuperJson\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"YourVendor\\LaravelSuperJson\\Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"providers": [
"YourVendor\\LaravelSuperJson\\SuperJsonServiceProvider"
],
"aliases": {
"SuperJson": "YourVendor\\LaravelSuperJson\\Facades\\SuperJson"
}
}
},
"scripts": {
"test": "vendor/bin/phpunit",
"analyse": "vendor/bin/phpstan analyse"
},
"minimum-stability": "dev",
"prefer-stable": true
}
```
--------------------------------
### Manual Serialization and Deserialization with SuperJson Facade
Source: https://context7.com/sulimanbenhalim/laravel-superjson/llms.txt
The SuperJson facade allows for direct serialization and deserialization of data in any PHP context. It supports converting data to a format suitable for embedding in HTML and can handle custom data types.
```php
use SulimanBenhalim\LaravelSuperJson\Facades\SuperJson;
use SulimanBenhalim\LaravelSuperJson\DataTypes\BigInt;
// Serialize data
$data = [
'timestamp' => now(),
'user_id' => new BigInt('9999999999999999'),
'tags' => new SuperSet(['php', 'laravel', 'api']),
];
$serialized = SuperJson::serialize($data);
// Returns: ['json' => [...], 'meta' => ['values' => [...]]]
// Deserialize back to PHP
$restored = SuperJson::deserialize($serialized);
// Deserialize from JSON string
$jsonString = json_encode($serialized);
$restored = SuperJson::deserialize($jsonString);
// Convert to HTML-safe JSON for embedding
$htmlSafe = SuperJson::toHtml($data);
echo "";
```
--------------------------------
### Handling URLs and RegExp with Serializable Classes
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/README.md
Shows how to use `SerializableUrl` and `SerializableRegex` from Laravel SuperJSON to ensure proper serialization of URL objects and regular expressions, preserving their structure and properties.
```php
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'
```
--------------------------------
### Using SuperSet and SuperMap for Collections in PHP
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/README.md
Illustrates the use of `SuperSet` for managing unique collections and `SuperMap` for key-value pairs with diverse key types in PHP, leveraging Laravel SuperJSON's data type extensions.
```php
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'
```
--------------------------------
### Git Ignore File (.gitignore)
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
Specifies intentionally untracked files that Git should ignore. This file prevents the inclusion of vendor directories, dependency lock files, IDE configurations, and temporary cache files in the repository.
```gitignore
/vendor
/node_modules
/.idea
/.vscode
/.vagrant
.phpunit.result.cache
.php-cs-fixer.cache
composer.lock
package-lock.json
.DS_Store
Thumbs.db
```
--------------------------------
### Configure SuperJSON Security and Behavior (PHP)
Source: https://context7.com/sulimanbenhalim/laravel-superjson/llms.txt
This PHP configuration file allows customization of SuperJSON's behavior, security settings, and transformers. It defines custom transformers, serialization options, automatic route middleware, type-to-JavaScript mappings, and critical security settings like allowed classes and depth limits. To apply these configurations, publish the configuration using 'php artisan vendor:publish --tag=superjson-config'.
```php
// config/superjson.php
return [
// Custom transformers
'transformers' => [
\App\Transformers\MoneyTransformer::class,
\App\Transformers\GeoLocationTransformer::class,
],
// Serialization options
'options' => [
'preserve_zero_fraction' => true,
'unescaped_unicode' => true,
'throw_on_error' => true,
'max_depth' => 512,
],
// Auto-apply middleware to route patterns
'auto_routes' => [
'api/*',
'v1/*',
'superjson/*',
],
// Type to JavaScript mappings
'type_mappings' => [
\DateTime::class => 'Date',
\DateTimeImmutable::class => 'Date',
\Carbon\Carbon::class => 'Date',
],
// Security settings - CRITICAL
'security' => [
'allow_class_restoration' => false, // Disable for security
'allowed_classes' => [
\App\ValueObjects\Money::class,
\App\ValueObjects\Address::class,
],
'max_array_size' => 1000,
'max_depth' => 10,
'sanitize_logged_content' => true,
'validate_input' => true,
],
];
// Publish configuration
// php artisan vendor:publish --tag=superjson-config
```
--------------------------------
### Use Laravel Response Macro for SuperJSON Output
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
This PHP code demonstrates how to use the `response()->superjson()` macro in a Laravel controller to return data in the SuperJSON format. It shows how to include various data types, such as `BigInt` and `SuperSet`, which will be correctly preserved by the package.
```php
// In your controller
return response()->superjson([
'user' => $user,
'created_at' => now(),
'big_id' => new BigInt('12345678901234567890'),
'tags' => new SuperSet(['php', 'laravel', 'json']),
]);
// Short alias
return response()->sjson($data);
```
--------------------------------
### Create Base Test Class with Orchestra Testbench for Laravel SuperJSON
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
This PHP code sets up a base test class for Laravel SuperJSON using Orchestra Testbench. It configures the testing environment, including the service provider and database connection, to ensure tests run reliably.
```php
set('database.default', 'testbench');
$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
// SuperJSON configuration for testing
$app['config']->set('superjson.options.throw_on_error', true);
}
}
```
--------------------------------
### Utilize SuperSet and SuperMap Collections in Laravel
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
Demonstrates the usage of `SuperSet` for unique collections and `SuperMap` for key-value pairs within Laravel, providing methods for adding, checking existence, removing elements, and setting/getting values. These are enhanced collection types compatible with SuperJSON.
```php
use YourVendor\LaravelSuperJson\Transformers\SuperSet;
use YourVendor\LaravelSuperJson\Transformers\SuperMap;
// Sets (unique values)
$tags = new SuperSet(['laravel', 'php', 'laravel']); // Duplicates removed
$tags->add('javascript');
$tags->has('php'); // true
$tags->remove('javascript');
// Maps (key-value pairs)
$settings = new SuperMap([
['theme', 'dark'],
['language', 'en'],
[123, 'numeric key'], // Any type as key
]);
$settings->set('theme', 'light');
$value = $settings->get('theme'); // 'light'
```
--------------------------------
### Implement Laravel SuperJSON Facade
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
This PHP facade provides a convenient, static interface for accessing Laravel SuperJSON's functionality. It allows easy calls to methods like `serialize`, `deserialize`, `registerTransformer`, and `toHtml` without needing to inject the SuperJSON class directly. The facade is registered with the service container under the name 'superjson'.
```php
mergeConfigFrom(
__DIR__.'/../config/superjson.php', 'superjson'
);
// Register the main SuperJson service
$this->app->singleton('superjson', function ($app) {
return new SuperJson(
config('superjson.transformers', []),
config('superjson.options', [])
);
});
// Register alias for facade
$this->app->alias('superjson', SuperJson::class);
}
/**
* Bootstrap services - Routes, views, macros, etc.
*/
public function boot(): void
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__.'/../config/superjson.php' => config_path('superjson.php'),
], 'superjson-config');
}
$this->registerResponseMacro();
$this->registerRequestMacro();
$this->registerBladeDirective();
$this->registerMiddleware();
}
/**
* Register the response()->superjson() macro
*/
protected function registerResponseMacro(): void
{
Response::macro('superjson', function ($data, $status = 200, array $headers = []) {
$serialized = app('superjson')->serialize($data);
return Response::json(
$serialized,
$status,
array_merge($headers, ['Content-Type' => 'application/superjson'])
);
});
// Shorter alias
Response::macro('sjson', function ($data, $status = 200, array $headers = []) {
return Response::superjson($data, $status, $headers);
});
}
/**
* Register the Request::superjson() helper
*/
protected function registerRequestMacro(): void
{
Request::macro('superjson', function ($key = null) {
$content = $this->getContent();
if (empty($content)) {
return null;
}
$deserialized = app('superjson')->deserialize($content);
return $key ? data_get($deserialized, $key) : $deserialized;
});
// Alias
Request::macro('sjson', function ($key = null) {
return $this->superjson($key);
});
}
/**
* Register Blade directive for embedding SuperJSON
*/
protected function registerBladeDirective(): void
{
Blade::directive('superjson', function ($expression) {
return "toHtml($expression); ?>";
});
}
/**
* Register middleware for automatic SuperJSON handling
*/
protected function registerMiddleware(): void
{
$this->app['router']->aliasMiddleware(
'superjson',
\YourVendor\LaravelSuperJson\Http\Middleware\HandleSuperJsonRequests::class
);
}
}
```
--------------------------------
### Access SuperJSON Data from Laravel Requests
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
Demonstrates how to retrieve SuperJSON encoded data from an incoming request using helper methods provided by the package. It shows accessing the entire data object or specific fields using dot notation. The `sjson()` alias is also presented.
```php
// Access SuperJSON data from requests
$data = $request->superjson();
$specificField = $request->superjson('user.name');
// Short alias
$data = $request->sjson();
```
--------------------------------
### Configure Laravel SuperJSON Settings
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
This PHP configuration file allows you to customize the behavior of Laravel SuperJSON. You can register custom transformers, define serialization options like preserving zero fractions and unescaped Unicode, specify routes for automatic JSON transformation, map PHP types to SuperJSON types, and configure security settings for deserialization.
```php
[
\YourVendor\LaravelSuperJson\Transformers\DateTransformer::class,
\YourVendor\LaravelSuperJson\Transformers\BigIntTransformer::class,
\YourVendor\LaravelSuperJson\Transformers\CollectionTransformer::class,
\YourVendor\LaravelSuperJson\Transformers\RegexTransformer::class,
\YourVendor\LaravelSuperJson\Transformers\UrlTransformer::class,
],
/*
|--------------------------------------------------------------------------
| Serialization Options
|--------------------------------------------------------------------------
|
| Configure how SuperJSON handles serialization and deserialization.
|
*/
'options' => [
'preserve_zero_fraction' => true,
'unescaped_unicode' => true,
'throw_on_error' => true,
'max_depth' => 512,
],
/*
|--------------------------------------------------------------------------
| Auto-Transform Routes
|--------------------------------------------------------------------------
|
| Define route patterns that should automatically use SuperJSON
| transformation via middleware.
|
*/
'auto_routes' => [
'api/*',
'superjson/*',
],
/*
|--------------------------------------------------------------------------
| Type Mappings
|--------------------------------------------------------------------------
|
| Map PHP classes to SuperJSON types for custom handling.
|
*/
'type_mappings' => [
\DateTime::class => 'Date',
\DateTimeImmutable::class => 'Date',
\Carbon\Carbon::class => 'Date',
],
/*
|--------------------------------------------------------------------------
| Security Settings
|--------------------------------------------------------------------------
|
| Configure security-related options for deserialization.
|
*/
'security' => [
'allow_class_restoration' => false,
'allowed_classes' => [],
'max_array_size' => 10000,
],
];
```
--------------------------------
### Apply SuperJSON Middleware in Laravel Routes
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
Illustrates how to apply the `superjson` middleware to routes in Laravel, ensuring that requests and responses handled by these routes utilize SuperJSON serialization. This is typically done within the `routes/api.php` file.
```php
// In routes/api.php
Route::middleware(['superjson'])->group(function () {
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
});
```
--------------------------------
### Middleware - Automatic Request/Response Transformation
Source: https://context7.com/sulimanbenhalim/laravel-superjson/llms.txt
Apply the `superjson` middleware to automatically handle SuperJSON requests and responses on specific routes or route groups.
```APIDOC
## Routes with SuperJSON Middleware
### Description
Apply the `superjson` middleware to automatically handle SuperJSON requests and responses on specific routes or route groups. This middleware transforms incoming SuperJSON requests into PHP objects with preserved types and outgoing PHP objects into SuperJSON responses.
### Method
All (GET, POST, PUT, DELETE, etc.)
### Endpoint
Depends on the routes it's applied to.
### Parameters
- None (applied via middleware configuration).
### Request Example
```php
// routes/api.php
use Illuminate\Support\Facades\Route;
// Apply to route group
Route::middleware(['superjson'])->group(function () {
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::put('/users/{id}', [UserController::class, 'update']);
});
// Apply to single route
Route::post('/api/data', function () {
$data = request()->superjson();
return response()->superjson($data);
})->middleware('superjson');
// In controller - types are automatically handled
class UserController extends Controller
{
public function store(Request $request)
{
// Data is already deserialized with types preserved
$data = $request->superjson();
$user = User::create([
'name' => $data['name'],
'registered_at' => $data['registered_at'], // DateTime object
]);
// Response is automatically serialized
return $user;
}
}
```
### Response
#### Success Response (200)
- The response body will be SuperJSON encoded if the return value is not null.
#### Response Example
```json
{
"id": 1,
"name": "Jane Doe",
"registered_at": {
"__datatype__": "datetime",
"__value__": "2023-10-27T11:00:00.000Z"
}
}
```
```
--------------------------------
### Implement Regex Transformer for Laravel SuperJSON
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
This PHP code defines a RegexTransformer and a SerializableRegex class. The transformer handles the serialization and deserialization of regular expressions, allowing them to be processed by SuperJSON. The SerializableRegex class provides methods for creating, converting, and matching regex patterns.
```php
toString();
}
public function restore($value): SerializableRegex
{
return SerializableRegex::fromString($value);
}
public function getType(): string
{
return 'regexp';
}
}
class SerializableRegex
{
private string $pattern;
private string $flags;
public function __construct(string $pattern, string $flags = '')
{
$this->pattern = $pattern;
$this->flags = $flags;
}
public static function fromString(string $regex): self
{
if (preg_match('/^\/(.*)\/([gimsuvy]*)$/', $regex, $matches)) {
return new self($matches[1], $matches[2]);
}
return new self($regex);
}
public function toString(): string
{
return "/{$this->pattern}/{$this->flags}";
}
public function match(string $subject): array
{
$phpFlags = $this->convertJsToPhpFlags($this->flags);
preg_match_all("/{$this->pattern}/{$phpFlags}", $subject, $matches);
return $matches[0] ?? [];
}
private function convertJsToPhpFlags(string $jsFlags): string
{
$phpFlags = '';
if (str_contains($jsFlags, 'i')) $phpFlags .= 'i';
if (str_contains($jsFlags, 'm')) $phpFlags .= 'm';
if (str_contains($jsFlags, 's')) $phpFlags .= 's';
if (str_contains($jsFlags, 'u')) $phpFlags .= 'u';
return $phpFlags;
}
}
```
--------------------------------
### Test Laravel API Responses and Requests with SuperJSON
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
This PHP code defines feature tests for the Laravel SuperJSON integration. It sets up test routes that utilize Laravel's response macros and middleware to handle SuperJSON data for both outgoing responses and incoming requests. The tests verify status codes, content types, and the correct parsing and preservation of data types, including BigInt.
```php
superjson([
'timestamp' => now(),
'big_number' => new BigInt('99999999999999999999'),
]);
})->middleware('superjson');
Route::post('/test-request', function () {
return response()->json([
'received' => request()->superjson(),
]);
})->middleware('superjson');
}
/** @test */
public function response_macro_works()
{
$response = $this->postJson('/test-superjson');
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/superjson');
$data = $response->json();
$this->assertArrayHasKey('json', $data);
$this->assertArrayHasKey('meta', $data);
$this->assertArrayHasKey('timestamp', $data['json']);
$this->assertArrayHasKey('big_number', $data['json']);
}
/** @test */
public function request_macro_works()
{
$superJsonData = [
'json' => [
'name' => 'Test',
'created' => '2023-10-05T12:00:00+00:00',
],
'meta' => [
'values' => [
'created' => ['Date'],
],
],
];
$response = $this->postJson('/test-request', $superJsonData, [
'Content-Type' => 'application/superjson',
]);
$response->assertStatus(200);
$received = $response->json('received');
$this->assertEquals('Test', $received['name']);
$this->assertNotNull($received['created']);
}
/** @test */
public function middleware_auto_transforms_responses()
{
$response = $this->postJson('/test-superjson', [], [
'Accept' => 'application/superjson',
]);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/superjson');
$data = $response->json();
$this->assertArrayHasKey('json', $data);
$this->assertArrayHasKey('meta', $data);
}
/** @test */
public function blade_directive_renders_correctly()
{
$view = view()->make('test-view', [
'data' => ['timestamp' => now()],
])->render();
// View content:
$this->assertStringContainsString('"json":', $view);
$this->assertStringContainsString('"meta":', $view);
}
}
```
--------------------------------
### Register Custom Transformer in PHP
Source: https://github.com/sulimanbenhalim/laravel-superjson/blob/main/plan.md
Allows for the registration of a custom transformer. It accepts an instance of `TypeTransformer` and adds it to the internal list of transformers. This enables extending the JSON serialization capabilities with custom logic.
```php
public function registerTransformer(TypeTransformer $transformer): void
{
$this->transformers[] = $transformer;
}
```
--------------------------------
### Request Macro - Deserializing Incoming Data
Source: https://context7.com/sulimanbenhalim/laravel-superjson/llms.txt
Access SuperJSON data from incoming requests with automatic type restoration using `request()->superjson()`. It automatically deserializes data preserving original types.
```APIDOC
## POST /api/events
### Description
Access SuperJSON data from incoming requests with automatic type restoration using `request()->superjson()`. It automatically deserializes data preserving original types.
### Method
POST
### Endpoint
/api/events
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- **data** (object) - Required - The SuperJSON encoded data from the request.
### Request Example
```php
use Illuminate\Http\Request;
Route::post('/api/events', function (Request $request) {
// Get all SuperJSON data with types preserved
$data = $request->superjson();
// Access nested data with dot notation
$timestamp = $request->superjson('event.timestamp');
// $timestamp is already a DateTime object, not a string
$event = Event::create([
'name' => $data['name'],
'scheduled_at' => $data['timestamp'], // Already DateTime
'max_participants' => $data['max_participants'], // BigInt if needed
]);
return response()->superjson($event, 201);
});
// Short alias
$data = $request->sjson('user.preferences');
```
### Response
#### Success Response (201)
- **event** (object) - The created event object with preserved types.
#### Response Example
```json
{
"id": 1,
"name": "New Event",
"scheduled_at": {
"__datatype__": "datetime",
"__value__": "2023-10-27T12:00:00.000Z"
},
"max_participants": {
"__datatype__": "bigint",
"__value__": "100"
}
}
```
```
--------------------------------
### Automatic Request/Response Transformation with Middleware
Source: https://context7.com/sulimanbenhalim/laravel-superjson/llms.txt
Apply the 'superjson' middleware to automatically handle SuperJSON requests and responses on specific routes or route groups. When applied, incoming request data is automatically deserialized with types preserved, and outgoing responses are automatically serialized. This eliminates the need for manual calls to request()->superjson() and response()->superjson() within controllers for routes covered by the middleware.
```php
// routes/api.php
use Illuminate\Support\Facades\Route;
// Apply to route group
Route::middleware(['superjson'])->group(function () {
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::put('/users/{id}', [UserController::class, 'update']);
});
// Apply to single route
Route::post('/api/data', function () {
$data = request()->superjson();
return response()->superjson($data);
})->middleware('superjson');
// In controller - types are automatically handled
class UserController extends Controller
{
public function store(Request $request)
{
// Data is already deserialized with types preserved
$data = $request->superjson();
$user = User::create([
'name' => $data['name'],
'registered_at' => $data['registered_at'], // DateTime object
]);
// Response is automatically serialized
return $user;
}
}
```