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 Eloquent Laravel Package

nilportugues/serializer-eloquent

Eloquent ORM driver for nilportugues/serializer. Serialize Laravel/Eloquent models and their relationships into the Serializer library’s normalized array format, handling common Eloquent edge cases so you can reuse one consistent serialization layer across your app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nilportugues/serializer-eloquent
    

    Ensure nilportugues/serializer is also installed (required dependency).

  2. Register the Driver: In your AppServiceProvider or a dedicated config file:

    use NilPortugues\Serializer\Serializer;
    use NilPortugues\Serializer\Driver\EloquentDriver;
    
    public function boot()
    {
        $serializer = new Serializer();
        $serializer->addDriver(new EloquentDriver());
        $this->app->singleton(Serializer::class, function () use ($serializer) {
            return $serializer;
        });
    }
    
  3. First Use Case: Serialize an Eloquent model to JSON:

    use NilPortugues\Serializer\Serializer;
    
    $user = User::find(1);
    $serializer = app(Serializer::class);
    $json = $serializer->serialize($user, 'json');
    

Implementation Patterns

Core Workflows

  1. Basic Serialization:

    // JSON
    $serializer->serialize($model, 'json');
    
    // JSON:API
    $serializer->serialize($model, 'jsonapi');
    
    // HAL+JSON
    $serializer->serialize($model, 'hal');
    
  2. Customizing Output:

    • Exclude Attributes:
      $serializer->setExcludedAttributes(['password', 'api_token']);
      
    • Include Relations:
      $serializer->setIncludedRelations(['posts', 'comments']);
      
  3. Nested Serialization:

    $post = Post::with('author.comments')->find(1);
    $serializer->serialize($post, 'jsonapi'); // Nested relations included
    
  4. API Resource Integration: Use with Laravel's JsonResource for hybrid workflows:

    $resource = new UserResource($user);
    $serializer->serialize($resource, 'json');
    

Integration Tips

  • Middleware for API Responses:

    // app/Http/Middleware/SerializeResponse.php
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if ($response->isJson()) {
            $data = $response->getData();
            $serialized = app(Serializer::class)->serialize($data, 'jsonapi');
            return response()->json($serialized, $response->status());
        }
        return $response;
    }
    
  • Dynamic Format Selection:

    $format = request()->header('Accept') === 'application/vnd.api+json' ? 'jsonapi' : 'json';
    $serializer->serialize($model, $format);
    
  • Caching Serialized Output:

    $cacheKey = 'user:'.$user->id.':jsonapi';
    $serialized = cache($cacheKey, function() use ($user) {
        return app(Serializer::class)->serialize($user, 'jsonapi');
    }, now()->addHours(1));
    

Gotchas and Tips

Pitfalls

  1. Outdated Dependencies:

    • The package hasn’t been updated since 2017. Test thoroughly with Laravel 5.5+ and PHP 7.2+.
    • Potential conflicts with newer Eloquent features (e.g., append, hidden, visible arrays in Laravel 8+).
  2. Relation Handling:

    • Nested relations may cause infinite recursion if not eager-loaded:
      // Fix: Ensure relations are loaded
      $model->load(['relation1', 'relation1.relation2']);
      
    • Circular references (e.g., User hasMany Post, Post belongsTo User) require explicit exclusion:
      $serializer->setExcludedAttributes(['posts.user']); // Break cycles
      
  3. JSON:API Compliance:

    • The jsonapi driver may not fully adhere to JSON:API spec (e.g., links, meta fields). Validate output with tools like jsonapi-test.
  4. Performance:

    • Serializing large datasets (e.g., User::all()) can be memory-intensive. Use pagination or chunking:
      User::cursor()->each(function ($user) {
          $serializer->serialize($user, 'json');
      });
      

Debugging

  • Inspect Serialization Rules:
    $driver = $serializer->getDriver('eloquent');
    dump($driver->getRules()); // View applied rules
    
  • Enable Verbose Output:
    $serializer->setDebug(true); // Logs serialization steps
    
  • Check for Deprecated Methods:
    • Override the driver to handle deprecated Eloquent methods (e.g., timestamps vs. $dates).

Extension Points

  1. Custom Drivers: Extend EloquentDriver to support additional formats or logic:

    class CustomEloquentDriver extends EloquentDriver
    {
        protected function getDefaultFormat()
        {
            return 'custom';
        }
    
        public function serializeToCustom($model)
        {
            // Custom logic
        }
    }
    
  2. Dynamic Attribute Mapping: Use getAttributes() to transform attributes on-the-fly:

    $serializer->setAttributeTransformer(function ($model, $attribute) {
        return strtoupper($attribute); // Example: Convert all attributes to uppercase
    });
    
  3. Event Hooks: Listen to serialization events (if supported in newer versions of nilportugues/serializer):

    $serializer->on('serializing', function ($model, $format) {
        // Pre-serialization logic
    });
    
  4. Fallback for Missing Attributes: Handle cases where attributes are missing in the model:

    $serializer->setDefaultValueForMissingAttributes(null); // or a default value
    

Config Quirks

  • Driver Registration Order: Ensure EloquentDriver is registered before other drivers to avoid conflicts.
  • Format Prioritization: The serialize() method uses the first matching driver. Explicitly specify formats to avoid ambiguity:
    $serializer->serialize($model, 'jsonapi'); // Not 'json'
    
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