Installation
composer require alexmanno/serializer
Register the service provider in config/app.php:
'providers' => [
// ...
Alexmanno\Serializer\SerializerServiceProvider::class,
],
Basic Usage
Inject the SerializerInterface into your controller/service:
use Alexmanno\Serializer\SerializerInterface;
public function __construct(private SerializerInterface $serializer) {}
// Serialize to JSON
$data = ['key' => 'value'];
$json = $this->serializer->serialize($data, 'json');
// Deserialize from JSON
$decoded = $this->serializer->deserialize($json, 'json', stdClass::class);
First Use Case Convert a Laravel Eloquent model to XML for an API response:
$user = User::find(1);
$xml = $this->serializer->serialize($user, 'xml');
return response($xml, 200)->header('Content-Type', 'application/xml');
API Responses Normalize complex nested data (e.g., relationships) before serialization:
$resource = new UserResource($user);
$json = $this->serializer->serialize($resource, 'json');
Configuration Files Load YAML config files dynamically:
$yaml = file_get_contents('config/settings.yml');
$config = $this->serializer->deserialize($yaml, 'yaml', 'array');
Data Migration Convert legacy XML data to JSON for modern APIs:
$legacyXml = file_get_contents('legacy/data.xml');
$json = $this->serializer->serialize(
$this->serializer->deserialize($legacyXml, 'xml', 'array'),
'json'
);
Laravel HTTP Responses Use middleware to auto-serialize responses:
$response = $this->serializer->serialize($data, request('format', 'json'));
return response($response, 200)->header('Content-Type', 'application/' . request('format'));
Form Request Validation Deserialize JSON/YAML payloads before validation:
$data = $this->serializer->deserialize(
request()->getContent(),
request('format', 'json'),
'array'
);
validator()->validate($data, $rules);
Caching Serialized Data Cache serialized payloads (e.g., API responses) with a TTL:
$cacheKey = 'user:1:serialized';
$serialized = Cache::remember($cacheKey, now()->addHours(1), function () use ($user) {
return $this->serializer->serialize($user, 'json');
});
Type Safety
stdClass or array loses type hints. Prefer concrete classes (e.g., User::class) for structured data.deserialize(..., 'json', User::class) with a custom JsonSerializable implementation.Circular References
User->posts->author->user) may cause infinite loops.__serialize()/__unserialize() or use ignore_errors:
$this->serializer->serialize($data, 'json', [], ['ignore_errors' => true]);
XML Namespaces
$xml = $this->serializer->serialize($data, 'xml', [], [
'xml_root_attributes' => ['xmlns' => 'http://example.com']
]);
YAML Anchors & Aliases
&id) may not deserialize correctly.Symfony\Component\Yaml\Parser directly or pre-process the YAML string.Enable Debug Mode
Pass ['debug' => true] to options to log serialization errors:
$this->serializer->serialize($data, 'json', [], ['debug' => true]);
Check Supported Formats Verify available formats with:
$this->serializer->getSupportedFormats(); // ['json', 'xml', 'yaml']
Custom Format Support
Extend the serializer by implementing FormatInterface:
class CsvFormat implements FormatInterface {
public function serialize($data, array $options) { ... }
public function deserialize($data, string $type, array $options) { ... }
}
Register it in config/serializer.php:
'formats' => [
'csv' => \App\Serializer\CsvFormat::class,
],
Global Options
Set default options in config/serializer.php:
'default_options' => [
'json' => ['pretty_print' => true],
'xml' => ['root' => 'response'],
],
Event Listeners
Listen to serializer.serializing/serializer.serialized events for pre/post-processing:
event(new SerializerEvent($data, 'json', $options));
How can I help you explore Laravel packages today?