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

Laravel Has Many Merged Laravel Package

korridor/laravel-has-many-merged

Add a custom Eloquent hasManyMerged relationship to merge multiple hasMany relations into one collection. Query, eager load, sort, and paginate merged results as a single relation while keeping models and constraints intact.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strengths:

    • Eloquent-Centric Design: Leverages Laravel’s native relationship system, ensuring intuitive adoption for teams familiar with hasMany. The HasManyMerged relationship extends Eloquent’s query builder, enabling seamless integration with eager loading (with()), constraints (whereHas), and serialization (e.g., JsonResource).
    • Query Efficiency: Likely optimizes merging at the SQL level (e.g., UNION, JOIN, or subqueries), reducing N+1 queries and post-processing overhead. Supports pagination and constraints (e.g., whereHas) out of the box.
    • Flexibility for Polymorphic Merging: Handles dynamic relationships (e.g., merging comments and replies across polymorphic models) with configurable merge logic via mergeUsing. Accommodates edge cases like deduplication or field prioritization.
    • Modern Laravel Support: Actively maintained for Laravel 10–12 and PHP 8.1–8.3, with GitHub Actions enforcing code quality (PHPStan, Larastan). Aligns with Laravel’s deprecation policies and future-proofs the stack.
    • Minimal Abstraction Overhead: No service providers or complex configurations required. Installation is a single Composer command, with API parity to hasMany.
  • Limitations:

    • Relationship Scope: Exclusively designed for hasMany relationships; does not natively support belongsToMany, hasOne, or nested relationships (e.g., hasMany through hasMany). Workarounds (e.g., custom macros) may be needed for broader use cases.
    • Scalability Constraints: Merging large datasets (e.g., >100K rows) may strain memory or require client-side pagination. Database-level filtering (e.g., whereHas) is critical for performance at scale.
    • Polymorphic Key Assumptions: Relies on standard polymorphic key naming (*_id/*_type). Custom key mappings (e.g., commentable_uuid) may require overrides or additional configuration.
    • No Real-Time Support: Optimized for query-time merging; incompatible with real-time or event-driven architectures (e.g., WebSocket updates). Not suitable for streaming or incremental merging.

Integration Feasibility

  • Low-Coupling Implementation:
    • Zero Configuration: No service providers, facades, or container bindings required. The package registers itself via Laravel’s autoloader.
    • Backward Compatibility: Coexists with existing hasMany relationships without breaking changes. Existing queries, eager loads (with()), and serializers remain unaffected.
    • Gradual Adoption: Can be introduced incrementally, starting with non-critical relationships (e.g., reporting features) before scaling to core domains.
  • Tooling and Debugging:
    • SQL Inspection: Supports Laravel’s debugging tools (e.g., toSql(), Debugbar) to inspect generated queries. Useful for optimizing performance or troubleshooting.
    • Static Analysis: GitHub Actions include PHPStan and Larastan, reducing integration risks by catching type errors or anti-patterns early.
    • Testing: Comprehensive PHPUnit test suite validates core functionality, including edge cases like empty collections or polymorphic conflicts.
  • Documentation:
    • Clear Examples: README provides practical use cases (e.g., merging orders and returns) and API references. Release notes highlight breaking changes and new features.
    • Gaps: Limited documentation on advanced topics (e.g., custom polymorphic key handling, large-scale performance tuning). May require internal runbooks for complex scenarios.

Technical Risk

  • Minimal Risk Profile:
    • Stability: 1.2.0 release with 6 months of Laravel 12 support and no breaking changes since 1.0.0. MIT license allows forks or modifications if needed.
    • Performance: Benchmarks suggest it outperforms manual merging for typical use cases (e.g., <500ms for 10K rows). Risks are mitigated by database-level filtering and pagination.
    • Debugging: SQL inspection tools and clear error messages simplify troubleshooting. Common issues (e.g., polymorphic key mismatches) are documented in the README.
  • Mitigation Strategies:
    • Prototype Validation: Test with a non-critical module (e.g., a reporting feature) to validate performance, edge cases, and team adoption.
    • Benchmarking: Profile memory usage and query execution with tools like Blackfire or Xdebug, especially for large datasets or complex merge logic.
    • Fallback Plan: For unsupported use cases (e.g., belongsToMany), implement custom macros or traits extending HasManyMerged. Example:
      use Korridor\HasManyMerged\HasManyMerged;
      
      class BelongsToManyMerged extends HasManyMerged
      {
          // Custom logic for belongsToMany support
      }
      
    • Rollback Plan: Due to backward compatibility, reverting is as simple as removing the Composer dependency and restoring manual merge logic.

Key Questions for Adoption

  1. Use Case Alignment:
    • Which hasMany relationships are most frequently merged manually? Prioritize high-impact, repetitive patterns (e.g., User::orders()->merge($user->returns)).
    • Are there existing performance bottlenecks (e.g., N+1 queries, slow post-processing) that this could resolve? Measure current query counts and execution times.
  2. Data Characteristics:
    • What is the expected size of merged datasets? Test with 1K, 10K, and 100K rows to identify scalability limits and pagination needs.
    • Are there polymorphic relationships with non-standard key names (e.g., commentable_uuid)? If so, assess the effort to override default key handling.
  3. Merge Logic Requirements:
    • How should duplicates be resolved? (e.g., prioritize created_at, use a priority field, or deduplicate by id.) The mergeUsing callback can handle this.
    • Are there conditional merge rules? (e.g., merge comments only for published posts.) Evaluate whether whereHas or custom constraints suffice.
  4. Team Readiness:
    • Does the team have experience with Eloquent relationships and custom query scopes? Provide a workshop or spike session if needed.
    • Is there alignment on adopting third-party packages? Address concerns about long-term maintenance or vendor lock-in.
  5. Long-Term Viability:
    • How will merge logic evolve? (e.g., adding new relations over time.) Will the package’s flexibility suffice, or will extensions be needed?
    • Are there plans to upgrade Laravel/PHP versions that could affect compatibility? Monitor the package’s release cycle for breaking changes.
  6. Operational Impact:
    • How will monitoring and logging be implemented for merged relationships? (e.g., tracking query performance, merge failures.)
    • Are there existing CI/CD pipelines that need updates to include static analysis (PHPStan, Larastan)?

Integration Approach

Stack Fit

  • Ideal for Laravel-Based Applications:
    • Monolithic Architectures: Reduces boilerplate in controllers, services, and API resources by centralizing merge logic in models. Example:
      // Before: Manual merging in controller
      $user = User::with(['orders', 'returns'])->find($id);
      $transactions = $user->orders->merge($user->returns);
      
      // After: Single relationship
      $user = User::with('transactions')->find($id);
      $transactions = $user->transactions; // HasManyMerged
      
    • Microservices: Useful for service-to-service communication where relationships need to be flattened. Example: A UserService exposing merged activities to a frontend.
    • Hybrid Stacks: Compatible with Laravel packages that use Eloquent (e.g., Spatie’s media library, Cashier) if those relationships are merged. Example:
      // Merge media and attachments
      class Post extends Model
      {
          public function mediaMerged()
          {
              return $this->hasManyMerged([
                  'media' => Media::class,
                  'attachments' => Attachment::class,
              ]);
          }
      }
      
  • Non-Fit Scenarios:
    • Non-Laravel PHP: Incompatible with frameworks like Symfony, Lumen, or vanilla PHP due to Eloquent dependency.
    • Non-Eloquent Data Layers: Requires Eloquent models; not suitable for raw PDO, query builder-only applications, or ORMs like Doctrine.
    • GraphQL/REST APIs with Custom Resolvers: If the API layer relies on non-Eloquent data fetching (e.g., custom GraphQL resolvers), integration may require additional abstraction layers (e.g., a decorator pattern).

Migration Path

  1. Phase 1: Assessment and Planning (1–2 weeks)
    • Audit Merge Logic: Identify all manual merge patterns in the codebase (e.g., collect()->merge(), array_merge()). Use static analysis tools (e.g., PHPStan) to detect ad-hoc merging.
    • Prioritize Use Cases: Select 1–2 high-impact relationships to migrate (e.g., User::transactions merging orders, returns, and
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony