Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Serializer Laravel Package

symfony/serializer

Symfony Serializer component for converting object graphs and data structures to/from arrays and formats like JSON or XML. Supports powerful normalizers/encoders, metadata, naming and type handling—ideal for APIs, messaging, and data interchange.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require symfony/serializer
    

    For Laravel, use symfony/serializer-pack for a pre-configured bundle (if needed).

  2. Basic Usage:

    use Symfony\Component\Serializer\Serializer;
    use Symfony\Component\Serializer\Encoder\JsonEncoder;
    use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
    
    $encoders = [new JsonEncoder()];
    $normalizers = [new ObjectNormalizer()];
    $serializer = new Serializer($normalizers, $encoders);
    
    // Serialize
    $data = $serializer->serialize($object, 'json');
    
    // Deserialize
    $object = $serializer->deserialize($json, 'object', 'App\\Model\\ClassName');
    
  3. First Use Case: Convert a Laravel Eloquent model to JSON for an API response:

    $user = User::find(1);
    $json = $serializer->serialize($user, 'json');
    return response($json, 200, ['Content-Type' => 'application/json']);
    

Key Entry Points

  • Serializer: Main class for serialization/deserialization.
  • Normalizer: Converts objects to/from arrays (e.g., ObjectNormalizer).
  • Encoder: Handles format conversion (e.g., JsonEncoder, XmlEncoder).
  • NameConverter: Maps property names (e.g., MetadataAwareNameConverter for Doctrine).

Implementation Patterns

Common Workflows

1. API Responses

Use ObjectNormalizer with JsonEncoder for Eloquent models:

$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
return response($serializer->serialize($model, 'json'));

Laravel Integration:

// In a controller
public function show(Model $model)
{
    return response()->json($this->serializer->serialize($model, 'json'));
}

2. Request Payload Parsing

Deserialize JSON into Eloquent models:

$data = json_decode(request()->getContent(), true);
$model = $serializer->deserialize($data, Model::class, 'json');

Validation-First Approach:

$validator = Validator::make($data, Model::$rules);
if ($validator->fails()) {
    return response()->json($validator->errors(), 422);
}
$model = $serializer->deserialize($data, Model::class, 'json');

3. Custom Normalizers

Extend ObjectNormalizer for domain-specific logic:

use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class CustomNormalizer implements NormalizerInterface
{
    public function normalize($object, string $format = null, array $context = [])
    {
        return [
            'id' => $object->id,
            'custom_field' => $object->getCustomField(),
        ];
    }

    public function supportsNormalization($data, string $format = null): bool
    {
        return $data instanceof YourModel;
    }
}

Register it in the Serializer constructor:

$normalizers = [new ObjectNormalizer(), new CustomNormalizer()];

4. Grouped Serialization

Use @Groups annotations to control which fields are serialized:

use Symfony\Component\Serializer\Annotation\Groups;

class User
{
    #[Groups(['public'])]
    public $name;

    #[Groups(['admin'])]
    public $email;
}

Serialize with groups:

$serializer->serialize($user, 'json', [
    AbstractNormalizer::GROUPS => ['public'],
]);

5. Circular References

Handle circular references in Eloquent relationships:

$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
    return $object->getId();
});

6. Laravel Service Provider

Bind the serializer in AppServiceProvider:

public function register()
{
    $this->app->singleton(Serializer::class, function ($app) {
        $encoders = [new JsonEncoder()];
        $normalizers = [new ObjectNormalizer()];
        return new Serializer($normalizers, $encoders);
    });
}

Inject via constructor:

public function __construct(private Serializer $serializer) {}

Integration Tips

Laravel Eloquent

  • Automatic JSON Conversion: Use ObjectNormalizer with JsonEncoder for automatic model-to-JSON conversion in API responses.

    $response = response()->json($this->serializer->serialize($model, 'json'));
    
  • Mass Assignment: Deserialize JSON into Eloquent models safely:

    $data = $serializer->deserialize($request->json()->all(), Model::class, 'json');
    $data->save(); // Handles mass assignment via fillable fields
    

API Platform

  • Symfony API Platform uses this package under the hood. Customize normalizers for @ApiResource entities:
    #[ApiResource(
        normalizationContext: ['groups' => ['public']],
        denormalizationContext: ['groups' => ['public']]
    )]
    class User {}
    

Testing

  • Mock Serializer:

    $serializer = $this->createMock(Serializer::class);
    $serializer->method('serialize')->willReturn('{"id":1}');
    
  • Assert JSON:

    $json = $serializer->serialize($model, 'json');
    $this->assertJson($json);
    

Performance

  • Cache Normalizers: Reuse Serializer instances (e.g., as a singleton in Laravel).

    $serializer = app(Serializer::class); // Reuse across requests
    
  • Avoid Redundant Normalization: Use AbstractNormalizer::SKIP_MISSING_NULL_VALUES to skip null checks:

    $serializer->serialize($model, 'json', [
        AbstractNormalizer::SKIP_MISSING_NULL_VALUES => true,
    ]);
    

Gotchas and Tips

Pitfalls

1. Circular References

  • Issue: Infinite loops when serializing objects with circular references (e.g., User->posts->author->user).
  • Fix: Use setCircularReferenceHandler:
    $normalizer->setCircularReferenceHandler(function ($object) {
        return $object->getId();
    });
    
  • Laravel Gotcha: Eloquent relationships can cause this. Use ->with() to eager-load and avoid N+1 queries.

2. Type Mismatches

  • Issue: Deserialization fails if JSON types don’t match PHP types (e.g., "string" for a DateTime field).
  • Fix: Use @Type annotations or custom normalizers:
    #[Type(name: "datetime")]
    public ?DateTimeInterface $createdAt = null;
    
  • Debug Tip: Enable AbstractNormalizer::IGNORED_ATTRIBUTES to log skipped fields:
    $serializer->serialize($model, 'json', [
        AbstractNormalizer::IGNORED_ATTRIBUTES => true,
    ]);
    

3. Property Visibility

  • Issue: Private/protected properties are ignored by default.
  • Fix: Enable ObjectNormalizer::IGNORED_ATTRIBUTES or use @AccessType:
    #[AccessType("public_method")]
    class Model {}
    
  • Laravel Tip: Use getAttributes() in models to expose private properties:
    public function getAttributes()
    {
        return ['id', 'name', 'created_at'];
    }
    

4. Groups Conflicts

  • Issue: @Groups annotations may not work as expected with nested objects.
  • Fix: Explicitly set groups in context:
    $serializer->serialize($model, 'json', [
        AbstractNormalizer::GROUPS => ['group1', 'group2'],
    ]);
    
  • Debug Tip: Check for typos in group names (case-sensitive).

5. Enum Handling

  • Issue: Backed enums may fail deserialization if the value doesn’t match.
  • Fix: Use allow_invalid_values in BackedEnumNormalizer:
    $normalizer = new BackedEnumNormalizer();
    $normalizer->setAllowInvalidValues(true);
    

6. DateTime Formatting

  • Issue: Dates serialize as ISO strings but may need custom formats.
  • Fix: Use @SerializedName or
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony