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 in Laravel
1. **Installation**:
   ```bash
   composer require symfony/serializer:^8.1

No additional configuration is needed for basic usage, but ensure compatibility with Symfony 8.1+ components.

  1. First Use Case: Serialize an Eloquent model to JSON with improved error handling:

    use Symfony\Component\Serializer\SerializerInterface;
    use Symfony\Component\Serializer\Encoder\JsonEncoder;
    use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
    
    $encoders = [new JsonEncoder()];
    $normalizers = [new ObjectNormalizer()];
    $serializer = new Serializer($normalizers, $encoders);
    
    $user = User::find(1);
    try {
        $json = $serializer->serialize($user, 'json');
    } catch (\Symfony\Component\Serializer\Exception\ExceptionInterface $e) {
        report($e); // Laravel's error reporting
        $json = json_encode(['error' => 'Serialization failed']);
    }
    
  2. Where to Look First:

    • Symfony Serializer v8.1 Documentation
    • src/Serializer.php (core class)
    • src/Normalizer/ (for custom normalizers)
    • New: Focus on ExceptionInterface improvements in Exception/ directory for better error handling.

Implementation Patterns

Common Workflows

1. Basic Serialization/Deserialization (Updated for v8.1)

// Serialize with improved error handling
$serializer->serialize($object, 'json');

// Deserialize with explicit type hints
$deserialized = $serializer->deserialize($json, User::class, 'json');

2. Custom Normalizers for Eloquent Models (v8.1 Compatibility)

Extend ObjectNormalizer with Symfony 8.1's new NormalizerAwareInterface if needed:

use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;

class EloquentNormalizer extends ObjectNormalizer implements NormalizerAwareInterface
{
    use NormalizerAwareInterface;

    public function normalize($object, string $format = null, array $context = [])
    {
        if ($object instanceof Model) {
            return [
                'id' => $object->getKey(),
                'attributes' => $object->getAttributes(),
                'relations' => $object->relations,
            ];
        }
        return parent::normalize($object, $format, $context);
    }
}

3. Grouped Serialization (APIs) with Deprecation Awareness

Use @Groups annotations while checking for deprecation warnings:

use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\Deprecated;

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

    #[Deprecated('Use email_address instead')]
    #[Groups(['admin'])]
    public string $email;
}

4. Handling API Requests (Deserialization with Validation)

Deserialize with stricter type checking:

$data = json_decode($request->getContent(), true);
$user = $serializer->deserialize($data, User::class, 'json', [
    AbstractNormalizer::IGNORED_ATTRIBUTES => ['password'], // Explicitly ignore
]);

5. Circular References with Improved Error Reporting

Enable circular reference handling with enhanced debugging:

$normalizers = [new ObjectNormalizer([], null, null, [
    'circular_reference_handler' => function ($object) {
        return $object->getId();
    },
    'debug' => true, // New in v8.1 for better error reporting
])];

6. Integration with Laravel HTTP Messages (Symfony 8.1 Compatibility)

Use Symfony\Component\HttpFoundation\Response with updated headers:

$response = new Response($serializer->serialize($data, 'json'));
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('X-Content-Type-Options', 'nosniff'); // Security best practice

Integration Tips

Laravel Service Provider (Updated for v8.1)

Register the serializer with improved dependency injection:

public function register()
{
    $this->app->singleton(SerializerInterface::class, function ($app) {
        $encoders = [new JsonEncoder()];
        $normalizers = [
            new ObjectNormalizer(null, null, null, [
                'debug' => $app->isLocal(), // Enable debug only in local env
            ]),
            new EloquentNormalizer(),
        ];
        return new Serializer($normalizers, $encoders);
    });
}

API Resource Integration (v8.1 Best Practices)

Extend JsonResource with explicit serialization groups:

use Illuminate\Http\Resources\Json\JsonResource;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Annotation\Groups;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        $serializer = app(SerializerInterface::class);
        return $serializer->normalize($this->resource, null, [
            AbstractNormalizer::GROUPS => ['api'],
            AbstractNormalizer::IGNORED_ATTRIBUTES => ['pivot'], // Explicitly ignore
        ]);
    }
}

Form Request Validation with Enhanced Error Handling

Deserialize and validate with Symfony 8.1's improved validation integration:

public function rules()
{
    $data = $this->serializer->deserialize($this->request->getContent(), stdClass::class, 'json');
    return [
        'name' => 'required|string|max:255',
        'email' => 'required|email|max:255',
    ];
}

public function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
    throw new \Symfony\Component\Serializer\Exception\ValidationFailedException(
        $validator->errors()->toArray()
    );
}

Gotchas and Tips

Pitfalls

  1. Deprecated Methods in v8.1

    • Issue: Methods like normalize() in ObjectNormalizer may trigger deprecation warnings.
    • Fix: Use SerializerInterface methods directly or update custom normalizers:
      // Old (deprecated)
      $normalizer->normalize($object);
      
      // New (recommended)
      $serializer->serialize($object, 'json');
      
  2. Improved Error Reporting (Bug #64296)

    • Issue: Normalization errors now provide more detailed stack traces.
    • Fix: Ensure your ExceptionHandler is configured to log these:
      try {
          $serializer->serialize($object, 'json');
      } catch (\Symfony\Component\Serializer\Exception\ExceptionInterface $e) {
          report($e); // Laravel's error reporting
      }
      
  3. Type Mismatches with Stricter Validation

    • Issue: Deserialization fails more strictly in v8.1.
    • Fix: Use allow_extra_attributes and ignore_unknown_properties:
      new ObjectNormalizer(null, null, null, [
          'ignore_unknown_properties' => true,
          'allow_extra_attributes' => false, // Default is now stricter
      ]);
      
  4. Circular References Without Handler

    • Issue: Infinite recursion errors are now more verbose.
    • Fix: Configure a circular_reference_handler with debug mode:
      new ObjectNormalizer(null, null, null, [
          'circular_reference_handler' => function ($object) {
              return $object->getKey();
          },
          'debug' => true,
      ]);
      
  5. Groups and Wildcards (Deprecation Warning)

    • Issue: Wildcard groups (*) may trigger deprecation warnings.
    • Fix: Explicitly define groups in your annotations or metadata:
      #[Groups(['user:read'])]
      public string $name;
      
  6. Timezone Handling in DateTimeNormalizer

    • Issue: Timezone defaults may change in v8.1.
    • Fix: Explicitly set the timezone:
      new DateTimeNormalizer('UTC');
      

Debugging Tips

  1. Enable Debug Mode for Normalizers Set debug: true in ObjectNormalizer for detailed error messages:

    new ObjectNormalizer(null, null, null, ['debug' => true]);
    
  2. Inspect Normalization Context with Enhanced Logging Pass a context array and log it for debugging:

    $context = [
        AbstractNormalizer::GROUPS => ['api'],
        'debug' => true,
    ];
    $serializer->serialize($object, 'json', $context);
    
  3. Check for Deprecated Annotations

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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope