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

Raw Hydrator Laravel Package

minionfactory/raw-hydrator

Raw Hydrator is a small PHP package for turning raw data (arrays/records) into hydrated objects with minimal overhead. Useful for fast mapping of database results or API payloads into DTOs/entities without a full ORM.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require minionfactory/raw-hydrator
    

    Add to config/app.php under providers:

    MinionFactory\RawHydrator\RawHydratorServiceProvider::class,
    
  2. First Use Case Fetch a single model with eager-loaded relations in one query:

    use MinionFactory\RawHydrator\Facades\RawHydrator;
    
    $user = RawHydrator::hydrate(
        User::class,
        'SELECT * FROM users WHERE id = ?',
        [1]
    );
    
  3. Where to Look First

    • Facade: RawHydrator (for quick usage).
    • Service Provider: RawHydratorServiceProvider (for binding custom hydrators).
    • Hydrator Contract: MinionFactory\RawHydrator\Contracts\Hydrator (for extending behavior).

Implementation Patterns

Core Workflows

  1. Basic Hydration

    // Single model
    $model = RawHydrator::hydrate(
        Model::class,
        'SELECT * FROM table WHERE id = ?',
        [1]
    );
    
    // Collection of models
    $models = RawHydrator::hydrateCollection(
        Model::class,
        'SELECT * FROM table WHERE active = ?',
        [1]
    );
    
  2. Hydrating with Relations

    $user = RawHydrator::hydrate(
        User::class,
        'SELECT users.*, posts.* FROM users
         LEFT JOIN posts ON posts.user_id = users.id
         WHERE users.id = ?',
        [1],
        ['posts' => ['posts.*']] // Define relation columns
    );
    
  3. Custom Hydrators Bind a custom hydrator for a model:

    RawHydrator::extend('App\Models\CustomModel', function () {
        return new class implements Hydrator {
            public function hydrate(array $data) {
                return new CustomModel($data);
            }
        };
    });
    
  4. Integration with Query Builder

    $query = DB::select('SELECT * FROM users WHERE ...');
    $models = RawHydrator::hydrateCollectionFromResults(
        User::class,
        $query
    );
    

Best Practices

  • Use for Complex Joins: Ideal when you need to fetch models + relations in a single query (avoids N+1).
  • Avoid for Simple CRUD: Overkill for basic find() or first() operations.
  • Leverage hydrateCollection: For bulk operations (e.g., admin dashboards, reports).
  • Define Relation Columns Explicitly: Prevents unexpected hydration of unrelated columns.

Gotchas and Tips

Pitfalls

  1. Column Mismatch Errors

    • If your raw SQL returns columns not defined in the model’s $fillable or $casts, hydration fails.
    • Fix: Use hydrate() with a custom hydrator or adjust your query to match the model’s expected structure.
  2. Relation Ambiguity

    • If multiple relations could map to the same column (e.g., posts.* and comments.* both include id), hydration may fail.
    • Fix: Explicitly define relation columns:
      ['posts' => ['posts.id as post_id', 'posts.title']]
      
  3. Transaction Conflicts

    • Raw hydrators bypass Eloquent’s event system (e.g., retrieved, saved). If you rely on these, wrap in a transaction or manually trigger events:
      $model->fireModelEvent('retrieved', false);
      
  4. Performance Overhead

    • Hydrating large datasets with deep relations can be memory-intensive.
    • Tip: Use chunk() or cursor() for pagination:
      DB::select('SELECT * FROM large_table')->chunk(100, function ($results) {
          RawHydrator::hydrateCollectionFromResults(Model::class, $results);
      });
      

Debugging Tips

  • Enable Query Logging:
    DB::enableQueryLog();
    $model = RawHydrator::hydrate(...);
    dd(DB::getQueryLog());
    
  • Inspect Raw Data:
    $rawData = DB::select('...');
    dd($rawData); // Verify structure before hydrating.
    
  • Use hydrateCollectionFromResults for Testing: Pass raw query results directly to isolate hydration logic from SQL issues.

Extension Points

  1. Custom Hydrators Implement MinionFactory\RawHydrator\Contracts\Hydrator for model-specific logic:

    class CustomHydrator implements Hydrator {
        public function hydrate(array $data) {
            $model = new CustomModel();
            $model->setRawAttributes($data);
            $model->customLogic();
            return $model;
        }
    }
    
  2. Relation Resolvers Extend relation handling by binding a custom resolver:

    RawHydrator::extendRelationResolver(function ($model, $relation, $columns) {
        // Custom logic to resolve relations from $columns
    });
    
  3. Event Hooks Listen for hydration events (via service provider):

    RawHydrator::hydrated(function ($model) {
        // Post-hydration logic
    });
    
  4. Database-Specific Optimizations Override the default query builder for specific databases (e.g., PostgreSQL JSON fields):

    RawHydrator::setQueryBuilder(function () {
        return DB::connection('pgsql')->getQueryBuilder();
    });
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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