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

api-platform/serializer

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require api-platform/serializer
    

    Register the ApiPlatform\Serializer\Serializer\SerializerItemNormalizer in your Laravel service provider (e.g., AppServiceProvider):

    use ApiPlatform\Serializer\Serializer\SerializerItemNormalizer;
    
    public function register()
    {
        $this->app->bind(SerializerItemNormalizer::class, function ($app) {
            return new SerializerItemNormalizer(
                $app->make('serializer.normalizer.context_builder'),
                $app->make('serializer.property_accessor'),
                $app->make('serializer.property_info_extractor'),
                $app->make('serializer.naming_strategy'),
                $app->make('serializer.object_to_populate_extractor'),
                $app->make('serializer.object_to_populate_validator'),
                $app->make('serializer.name_converter')
            );
        });
    }
    
  2. First Use Case Serialize a Laravel Eloquent model to JSON:

    use ApiPlatform\Serializer\Serializer\SerializerInterface;
    
    $serializer = app(SerializerInterface::class);
    $data = $serializer->serialize(new User(), 'json');
    
    // Output: {"id":1,"name":"John Doe","email":"john@example.com"}
    
  3. Where to Look First

    • Documentation: API Platform Serializer Docs (even if standalone, concepts apply).
    • Source Code: Focus on SerializerItemNormalizer and Serializer classes in src/Serializer/.
    • Laravel Integration: Check vendor/api-platform/serializer/src/Serializer/ for core logic and vendor/api-platform/core (if installed) for Laravel-specific extensions.

Implementation Patterns

Common Workflows

  1. Basic Serialization Serialize Eloquent models, collections, or arrays:

    $serializer = app(SerializerInterface::class);
    $user = User::find(1);
    $serialized = $serializer->serialize($user, 'json');
    
  2. Deserialization Convert JSON back to PHP objects/arrays:

    $data = '{"name":"Jane","email":"jane@example.com"}';
    $deserialized = $serializer->deserialize($data, User::class, 'json');
    
  3. Context Customization Pass context to control serialization (e.g., groups, ignore nulls):

    $context = [
        'groups' => ['public'],
        'ignore_null_values' => true,
    ];
    $serializer->serialize($user, 'json', $context);
    
  4. Normalizer Chaining Extend or replace normalizers (e.g., for custom types):

    $normalizers = [
        new \ApiPlatform\Serializer\Normalizer\DateTimeNormalizer(),
        new \ApiPlatform\Serializer\Normalizer\ObjectNormalizer(),
        new \YourApp\CustomNormalizer(),
    ];
    $serializer = new Serializer($normalizers, []);
    
  5. Laravel-Specific Integration

    • API Responses: Use in App\Http\Middleware\TransformsResponse or controllers:
      return response()->json($serializer->serialize($data, 'json'));
      
    • Form Requests: Deserialize incoming requests:
      $validated = $serializer->deserialize($request->getContent(), StoreUserDto::class, 'json');
      
  6. Dynamic Metadata Use ApiPlatform\Metadata\Operation or ApiPlatform\Metadata\Property for runtime serialization rules (if paired with api-platform/core).


Integration Tips

  1. Leverage Laravel’s Service Container Bind the serializer as a singleton in AppServiceProvider for reuse:

    $this->app->singleton(SerializerInterface::class, function ($app) {
        return new Serializer($app->make('serializer.normalizers'), []);
    });
    
  2. Compose with Laravel’s HTTP Layer Integrate with Illuminate\Http\Request and Illuminate\Http\Response:

    $request->getContent(); // Deserialize
    response()->json($serializer->serialize($data)); // Serialize
    
  3. Use with Laravel Collections Serialize collections efficiently:

    $users = User::all();
    $serialized = $serializer->serialize($users->toArray(), 'json');
    
  4. Custom Naming Strategies Override default naming (e.g., snake_case to camelCase):

    use ApiPlatform\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
    
    $nameConverter = new CamelCaseToSnakeCaseNameConverter();
    $serializer = new Serializer($normalizers, [], $nameConverter);
    
  5. Event-Driven Extensions Listen to serializer.normalize events (if using Laravel Events) to modify output dynamically.


Gotchas and Tips

Pitfalls

  1. Circular References

    • Issue: Serializing objects with circular references (e.g., User hasMany Post, Post belongsTo User) throws Maximum function nesting level errors.
    • Fix: Use max_depth in context or implement a custom normalizer:
      $context = ['max_depth' => 2];
      
  2. Type Mismatches

    • Issue: Deserializing JSON into non-matching PHP types (e.g., string vs int).
    • Fix: Use ApiPlatform\Serializer\Normalizer\ObjectNormalizer with strict type checking or validate input first.
  3. Laravel-Specific Quirks

    • Issue: Eloquent relationships may not serialize as expected (e.g., lazy-loaded relationships).
    • Fix: Eager-load relationships or use ApiPlatform\Serializer\Normalizer\DateTimeNormalizer for dates.
  4. Performance Overhead

    • Issue: Serializing large datasets (e.g., 10,000+ records) can be slow.
    • Fix: Use chunking or limit fields with groups or attributes.
  5. Context Overrides

    • Issue: Context settings (e.g., groups) may not propagate as expected in nested objects.
    • Fix: Use context_builder to merge or override contexts dynamically.

Debugging Tips

  1. Enable Verbose Output Inspect normalizer calls by adding debug logging:

    $serializer->serialize($data, 'json', ['debug' => true]);
    
  2. Check Normalizer Order Ensure custom normalizers run after default ones (order matters):

    $normalizers = [
        new \ApiPlatform\Serializer\Normalizer\ObjectNormalizer(),
        new \YourApp\CustomNormalizer(), // Runs after ObjectNormalizer
    ];
    
  3. Validate Deserialization Use ApiPlatform\Serializer\Validator\ValidatorInterface to catch deserialization errors early:

    $validator = app(ValidatorInterface::class);
    $validator->validate($deserializedData, $context);
    
  4. Inspect Metadata Dump metadata for complex objects:

    $propertyInfoExtractor = app('serializer.property_info_extractor');
    $metadata = $propertyInfoExtractor->getMetadataForClass(User::class);
    dd($metadata);
    

Extension Points

  1. Custom Normalizers Create a normalizer for unsupported types (e.g., Carbon\Carbon):

    use ApiPlatform\Serializer\Normalizer\NormalizerInterface;
    
    class CarbonNormalizer implements NormalizerInterface
    {
        public function normalize($object, string $format = null, array $context = [])
        {
            return $object->format(\DateTime::ATOM);
        }
        // ... other required methods
    }
    
  2. Context Builders Dynamically build context based on request:

    use ApiPlatform\Serializer\Serializer\SerializerContextBuilderInterface;
    
    class LaravelContextBuilder implements SerializerContextBuilderInterface
    {
        public function createFromRequest(Request $request): array
        {
            return [
                'groups' => $request->query('groups', []),
                'locale' => app()->getLocale(),
            ];
        }
    }
    
  3. Name Converters Modify property naming (e.g., for API versioning):

    use ApiPlatform\Serializer\NameConverter\NameConverterInterface;
    
    class VersionedNameConverter implements NameConverterInterface
    {
        public function convertName(string $propertyName): string
        {
            return 'v1_'.$propertyName;
        }
    }
    
  4. Property Accessors Override property access for private/protected fields:

    use ApiPlatform\Serializer\PropertyAccessor\PropertyAccessorInterface;
    
    class LaravelPropertyAccessor implements PropertyAccessorInterface
    {
        public function getValue(object $object, string $property): mixed
        {
            return $object->{$
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky