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

botanick/serializer

Laravel/PHP serializer package for converting objects and arrays to structured formats and back. Aims to simplify data transformation with configurable normalization/denormalization for APIs, DTOs, and persistence layers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require botanick/serializer
    

    Add the service provider to config/app.php:

    'providers' => [
        Botanick\Serializer\SerializerServiceProvider::class,
    ],
    
  2. Basic Usage Register a serializer for a model in a service provider or boot method:

    $this->app->bind('serializer.my_model', function () {
        return new Botanick\Serializer\Serializers\JsonApiSerializer(MyModel::class);
    });
    
  3. First Use Case: Serializing a Model

    use Botanick\Serializer\Facades\Serializer;
    
    $model = MyModel::find(1);
    $serialized = Serializer::serialize($model, 'my_model');
    

Key Files to Review

  • config/serializer.php (default configuration)
  • src/Serializers/ (built-in serializer classes)
  • src/Contracts/SerializerInterface.php (core interface)

Implementation Patterns

Common Workflows

1. Model Serialization

  • Default Serializer: Use JsonApiSerializer for API responses:
    $serializer = new Botanick\Serializer\Serializers\JsonApiSerializer(MyModel::class);
    $serializer->serialize($model);
    
  • Custom Fields: Override fields() in a custom serializer:
    class CustomSerializer extends JsonApiSerializer {
        protected function fields() {
            return ['id', 'name', 'custom_field'];
        }
    }
    

2. Resource Serialization (Collections)

  • Automatically serialize collections with serializeCollection():
    $serializer = app('serializer.my_model');
    $serialized = $serializer->serializeCollection(MyModel::all());
    

3. Integration with Laravel HTTP Responses

  • Use the SerializerResponse helper for API responses:
    return SerializerResponse::make($model, 'my_model');
    

4. Dynamic Serializer Binding

  • Bind serializers dynamically based on request parameters:
    $serializerName = request()->input('serializer', 'default');
    $serializer = app("serializer.{$serializerName}");
    

5. Nested Relationships

  • Enable nested serialization in JsonApiSerializer:
    protected function relationships() {
        return ['user', 'posts']; // Nested fields
    }
    

Integration Tips

API Controllers

  • Use dependency injection for serializers:
    public function show(MyModel $model, JsonApiSerializer $serializer) {
        return $serializer->serialize($model);
    }
    

Form Requests

  • Validate and serialize in a single request:
    public function rules() {
        return ['id' => 'required|exists:my_models,id'];
    }
    
    public function withValidator($validator) {
        $validator->after(function ($validator) {
            $serializer = app('serializer.my_model');
            $validator->errors()->add('serialized_data', $serializer->serialize($this->input('data')));
        });
    }
    

Events and Observers

  • Trigger serialization on model events (e.g., retrieved):
    MyModel::retrieved(function ($model) {
        $serialized = app('serializer.my_model')->serialize($model);
        // Log or cache $serialized
    });
    

Testing

  • Mock serializers in tests:
    $this->app->instance('serializer.my_model', Mockery::mock(JsonApiSerializer::class));
    

Gotchas and Tips

Pitfalls

  1. Circular References

    • Nested serializers may cause infinite loops if relationships are bidirectional.
    • Fix: Use protected $includeDepth = 1; in JsonApiSerializer to limit depth.
  2. Missing Serializer Bindings

    • Forgetting to bind a serializer will throw BindingResolutionException.
    • Fix: Ensure all serializers are registered in a service provider.
  3. Performance with Large Collections

    • Serializing thousands of records can be slow.
    • Fix: Use serializeCollection() with pagination or chunking.
  4. Overriding Default Config

    • Changes to config/serializer.php may not reflect in runtime if cached.
    • Fix: Run php artisan config:clear after changes.
  5. Type Mismatches

    • Serializers assume models are Eloquent instances.
    • Fix: Extend JsonApiSerializer for non-model data:
      class ArraySerializer extends JsonApiSerializer {
          public function serialize($data) {
              return json_encode($data);
          }
      }
      

Debugging Tips

  1. Enable Debug Mode Add to config/serializer.php:

    'debug' => env('APP_DEBUG', false),
    

    Logs serialization steps to storage/logs/serializer.log.

  2. Inspect Serializer Output Use dd() or dump() to debug fields/relationships:

    $serializer = app('serializer.my_model');
    dump($serializer->fields(), $serializer->relationships());
    
  3. Check for Deprecated Methods

    • Monitor deprecation notices in Laravel 8+ for SerializerFacade usage.

Extension Points

  1. Custom Serializers

    • Extend Botanick\Serializer\Serializers\BaseSerializer for new formats (e.g., XML):
      class XmlSerializer extends BaseSerializer {
          public function serialize($data) {
              return $this->toXml($data);
          }
      }
      
  2. Dynamic Field Selection

    • Use middleware to filter fields based on user roles:
      $serializer->fields(['id', 'name']); // Override dynamically
      
  3. Caching Serialized Output

    • Cache responses in JsonApiSerializer:
      protected function serialize($data) {
          return Cache::remember("serialized_{$data->id}", now()->addHours(1), function () use ($data) {
              return parent::serialize($data);
          });
      }
      
  4. GraphQL-like Serialization

    • Implement include and exclude parameters:
      $serializer->include(['user', 'posts'])->exclude(['deleted_at'])->serialize($model);
      
  5. Validation Integration

    • Validate serialized data against a schema (e.g., JSON Schema):
      use Botanick\Serializer\Validation\JsonSchemaValidator;
      
      $validator = new JsonSchemaValidator($serializedData, $schema);
      if ($validator->fails()) {
          throw new \InvalidArgumentException($validator->errors());
      }
      
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