PHP code example of sulimanbenhalim / laravel-superjson
1. Go to this page and download the library: Download sulimanbenhalim/laravel-superjson library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
sulimanbenhalim / laravel-superjson example snippets
// 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);
// Parse SuperJSON from incoming requests
$data = request()->superjson();
$user = request()->superjson('user.name');
// Short alias
$data = request()->sjson();
// Use API routes (no CSRF protection)
Route::post('/api/data', function() {
$data = request()->superjson();
return response()->superjson($result);
});
use SulimanBenhalim\LaravelSuperJson\DataTypes\BigInt;
$bigNumber = new BigInt('12345678901234567890');
$bigNumber->toString(); // "12345678901234567890"
$bigNumber->toInt(); // Converts to int if safe
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'
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'
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());