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

Compoships Eager Limit Laravel Package

mpyw/compoships-eager-limit

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package:

    composer require mpyw/compoships-eager-limit
    

    Ensure topclaudy/compoships (^2.0.4) and staudenmeir/eloquent-eager-limit (^1.7.1) are also installed (handled automatically via dependencies).

  2. Publish Config (if needed): The package extends compoships and eloquent-eager-limit without requiring additional configuration. No config file is published by default.

  3. First Use Case: Replace eager-loading with with() in your Compoships relationships to limit nested eager-loaded results:

    // Before (unlimited eager-load)
    $posts = Post::with('comments.user')->get();
    
    // After (limited eager-load)
    $posts = Post::with(['comments' => function ($query) {
        $query->limit(5)->with(['user' => function ($query) {
            $query->limit(3); // Nested limit
        }]);
    }])->get();
    

Implementation Patterns

Core Workflow

  1. Compoships + Eager-Limit Integration: Use with() clauses on Compoships relationships to apply limits to nested eager-loaded models. The package bridges compoships' polymorphic/morph-many relationships with eloquent-eager-limit's query constraints.

  2. Nested Relationships: Chain with() calls to limit results at any depth:

    $user = User::with([
        'posts' => function ($query) {
            $query->limit(10)->where('published', true);
        },
        'roles' => function ($query) {
            $query->limit(3)->orderBy('name');
        }
    ])->find(1);
    
  3. Dynamic Limits: Pass limits dynamically via closures or helper methods:

    $limit = request()->input('comments_limit', 5);
    $posts = Post::with(['comments' => fn($q) => $q->limit($limit)])->get();
    
  4. Performance Optimization:

    • Avoid N+1 Queries: Always use with() for relationships you intend to access.
    • Selective Loading: Combine with select() to reduce payload:
      $posts = Post::with(['comments.user' => fn($q) => $q->limit(2)])
          ->select('id', 'title')
          ->get();
      
  5. Compoships-Specific Patterns:

    • Polymorphic Relationships:
      $item = Item::with(['comments' => fn($q) => $q->limit(5)])->find(1);
      
    • Morph-Many:
      $user = User::with(['morphComments' => fn($q) => $q->limit(3)])->find(1);
      
  6. Query Scoping: Extend the package’s behavior by creating custom scopes:

    // app/Models/Post.php
    public function scopeWithLimitedComments($query, $limit = 5) {
        return $query->with(['comments' => fn($q) => $q->limit($limit)]);
    }
    

    Usage:

    $posts = Post::withLimitedComments(10)->get();
    

Gotchas and Tips

Pitfalls

  1. Laravel 11+ Compatibility:

    • The package exists as a workaround for compoships not yet supporting Laravel 11’s built-in eloquent-eager-limit. Monitor PR #180 for deprecation.
    • Action: If upgrading to Laravel 11+, evaluate whether to:
      • Remove this package and rely on compoships + core eloquent-eager-limit.
      • Fork the package to maintain compatibility.
  2. Over-Limiting:

    • Setting limit(0) or negative values may break queries. Validate inputs:
      $limit = max(1, (int) request('limit', 10));
      
  3. Caching Quirks:

    • Eager-loaded limits are not cached by default. If using remember() or replicate(), ensure limits are reapplied:
      $posts = Post::with(['comments' => fn($q) => $q->limit(5)])->remember(60)->get();
      
  4. Ordering Conflicts:

    • Limits interact with orderBy(). Ensure consistent ordering when combining:
      // Avoid: Unpredictable results if `created_at` is not indexed.
      $query->limit(5)->orderBy('created_at');
      
  5. Compoships-Specific Issues:

    • Morph Map Conflicts: If using custom morph maps, ensure the package’s eager-limit logic doesn’t interfere:
      // app/Models/Comment.php
      protected $morphClass = 'Commentable';
      
    • Polymorphic Constraints: Complex whereMorphTo or whereMorphLike queries may not play well with limits. Test thoroughly.

Debugging Tips

  1. Query Logging: Enable Laravel’s query logging to verify limits are applied:

    \DB::enableQueryLog();
    $posts = Post::with(['comments' => fn($q) => $q->limit(3)])->get();
    dd(\DB::getQueryLog());
    
  2. Isolation Testing: Test limits in isolation to rule out other query builders:

    // Test the limit alone
    $comments = Comment::where('post_id', 1)->limit(3)->get();
    
  3. Package Overrides: If the package doesn’t work as expected, check for method overrides in compoships or eloquent-eager-limit:

    composer show -a | grep "compoships\|eloquent-eager-limit"
    

Extension Points

  1. Custom Limit Macros: Add reusable limit logic via macros:

    // app/Providers/AppServiceProvider.php
    use Illuminate\Database\Eloquent\Builder;
    
    public function boot() {
        Builder::macro('withPaginated', function ($relation, $perPage = 10) {
            return $this->with([$relation => fn($q) => $q->limit($perPage)]);
        });
    }
    

    Usage:

    $posts = Post::withPaginated('comments', 5)->get();
    
  2. Event Listeners: Hook into eloquent.eager.loaded to post-process limited results:

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        'eloquent.eager.loaded' => [\App\Listeners\LogLimitedResults::class],
    ];
    
  3. Service Provider Binding: Bind custom limit strategies:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->bind(\Mpyw\ComposhipsEagerLimit\LimitStrategy::class, function () {
            return new \App\Services\CustomLimitStrategy();
        });
    }
    
  4. Testing: Use the package’s test suite as a reference for edge cases:

    composer test
    

    Focus on:

    • Nested limits.
    • Polymorphic relationships.
    • Query constraint interactions (e.g., where, orderBy).`
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager