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

Adds a “hasManyMerged” Eloquent relationship to merge multiple hasMany relations into one, so you can query, eager load, paginate, and sort related models through a single unified relation—ideal for combining items from different sources or tables.

View on GitHub
Deep Wiki
Context7

Getting Started

Start by installing the package via Composer:

composer require korridor/laravel-has-many-merged

Then, define merged relationships in your Eloquent models using the HasManyMerged trait and the mergedHasMany() method. For example, if a User has many posts and comments, you can merge them into a single activity relationship:

use Korridor\LaravelHasManyMerged\HasManyMerged;

class User extends Model
{
    use HasManyMerged;

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function activity()
    {
        return $this->mergedHasMany([
            'posts' => $this->posts(),
            'comments' => $this->comments(),
        ], 'created_at', 'desc');
    }
}

Your first use case will likely be loading a combined feed: User::with('activity')->get()->first()->activity.

Implementation Patterns

  • Unified feed APIs: Encapsulate all user activity in one relationship for use in APIs, notifications, or UI components (e.g., a timeline of Post and Comment instances).
  • Centralized sorting/filtering: Apply consistent orderBy, where, and limit rules in one place instead of manually merging collections post-query:
    $user->activity()->where('status', 'published')->limit(20)->get();
    
  • Polymorphic-like aggregation without schema changes: Simulate polymorphic relations by merging unrelated tables (e.g., notes, logs, tasks) into activity, even when they don’t share a common table.
  • Eager loading and constraints: Use with('activity') and eager-load constraints just like native relationships; the package handles merging logic at query time.
  • Extending behavior: Add scoped accessors or scopes that build on the merged relationship:
    public function scopeRecentActivity($query)
    {
        return $query->with(['activity' => fn($q) => $q->limit(10)]);
    }
    

Gotchas and Tips

  • Column alignment: All merged relations must share the same column names for ordering/filtering (e.g., all must have created_at, status, etc.). If they don’t, use selectRaw() or accessor mapping in the mergedHasMany() definition to homogenize fields.
  • Query builder vs collection merging: This merges queries, not collections—avoid performance pitfalls with large datasets by always using query constraints (e.g., limit, where) before get().
  • Ordering consistency: The third argument ('created_at', 'desc') in mergedHasMany() applies globally; if relations have different column names (e.g., updated_at), alias columns in the relationship’s base queries:
    $this->posts()->selectRaw('*, created_at as unified_timestamp')
    
  • Pagination Caveats: Direct paginate() on merged relations may produce incorrect offsets due to subquery merging. Prefer simplePaginate() or implement cursor-based pagination if exact counts aren’t required.
  • Scout / Search Integration: If using ElasticSearch/Scout, this pattern doesn’t natively index merged data—consider building custom search drivers or syncing a denormalized activity model.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport