Installation:
composer require nilportugues/serializer
Add the service provider to config/app.php under providers:
NilPortugues\Serializer\SerializerServiceProvider::class,
Basic Usage:
use NilPortugues\Serializer\Serializer;
$serializer = app(Serializer::class);
$data = ['name' => 'John', 'age' => 30, 'active' => true];
// Serialize to JSON
$json = $serializer->serialize($data, 'json');
echo $json; // '{"name":"John","age":30,"active":true}'
// Unserialize from JSON
$unserialized = $serializer->unserialize($json, 'json');
print_r($unserialized); // ['name' => 'John', ...]
First Use Case: Convert Eloquent models to JSON for API responses:
$user = User::find(1);
$responseData = $serializer->serialize($user, 'json');
return response()->json($responseData);
API Response Handling:
public function show(User $user)
{
return response()->json(
$this->serializer->serialize($user, 'json', [
'attributes' => ['id', 'name', 'email'],
'relations' => ['posts']
])
);
}
Caching Serialized Data:
$cacheKey = 'user:1:serialized';
$serialized = cache($cacheKey);
if (!$serialized) {
$user = User::find(1);
$serialized = $this->serializer->serialize($user, 'json');
cache()->put($cacheKey, $serialized, now()->addHour());
}
Form Request Validation:
public function rules()
{
return [
'user_data' => 'required|string',
];
}
public function validated($data)
{
$unserialized = $this->serializer->unserialize($data['user_data'], 'json');
return $unserialized;
}
Custom Serialization: Register custom handlers for specific classes:
$serializer->addHandler('App\Models\CustomModel', function ($model) {
return ['id' => $model->id, 'custom_field' => $model->customField];
});
Middleware for API: Create middleware to auto-serialize responses:
public function handle($request, Closure $next)
{
$response = $next($request);
if ($response->isJson()) {
$data = $response->getData(true);
$serialized = $this->serializer->serialize($data, 'json');
$response->setContent($serialized);
}
return $response;
}
Queue Jobs: Serialize job payloads to reduce memory usage:
$job = new ProcessOrder($order->id);
$job->setSerializedPayload($this->serializer->serialize($order, 'json'));
dispatch($job);
Deprecated Package:
spatie/array-to-xml, jenssegers/date, or Laravel’s built-in json_encode()/json_decode().Performance Overhead:
Security Risks:
$trustedData = $this->serializer->unserialize($input, 'json', [
'allowed_formats' => ['json', 'array'], // Restrict formats
]);
Configuration Quirks:
DateTime, Carbon).$serializer->setDefaultHandlers([
'datetime' => function ($date) {
return $date->format('Y-m-d H:i:s');
},
]);
Validate Serialized Output:
$serialized = $this->serializer->serialize($data, 'json');
$unserialized = $this->serializer->unserialize($serialized, 'json');
if (!hash_equals($serialized, $this->serializer->serialize($unserialized, 'json'))) {
throw new \RuntimeException('Serialization round-trip failed!');
}
Log Custom Handlers: Add debug logs for custom serializers:
$serializer->addHandler('App\Models\Post', function ($post) {
\Log::debug('Serializing Post', ['post' => $post->toArray()]);
return $post->toArray();
});
Handle Circular References:
The package may not handle circular references (e.g., User->posts->author->user). Use a workaround:
$serializer->setOption('circular_reference_handler', function ($object) {
return '[Circular Reference]';
});
Add Custom Formats: Extend support for formats like YAML or MessagePack:
$serializer->addFormat('yaml', function ($data) {
return \Spatie\ArrayToXml\ArrayToXml::convert($data);
}, function ($string) {
return yaml_parse($string);
});
Event-Based Serialization: Listen to serialization events (if supported) to modify output dynamically:
$serializer->on('serializing', function ($data, $format) {
if ($format === 'json') {
$data['timestamp'] = now()->toIso8601String();
}
});
Fallback for Missing Handlers: Provide a fallback for unsupported types:
$serializer->setFallbackHandler(function ($value) {
return is_object($value) ? get_class($value) : $value;
});
How can I help you explore Laravel packages today?