korridor/laravel-has-many-merged
Laravel package adding a “hasManyMerged” relationship to combine results from multiple hasMany relations into one merged collection/query. Useful for aggregating related models across different types or sources while keeping a familiar Eloquent API.
Strengths:
hasMany relationships without requiring raw SQL or complex query builder logic. Aligns with Laravel’s convention-over-configuration paradigm, reducing cognitive load for developers.Comment on Post, Article, and Video).with()).mergeUsing, catering to edge cases without forking the package.Fit for Complex Scenarios:
UserActivity combining logins, purchases, and support_tickets).Revenue merging sales, subscriptions, and refunds).Limitations:
hasMany through hasMany through hasMany). For these, raw SQL or a graph database may be better.hasMany: Doesn’t support merging other relationship types (e.g., belongsToMany, hasOne). Would need custom logic or a wrapper.composer require), and no service provider or configuration is needed. The API mirrors Laravel’s native relationships, so adoption is intuitive for Eloquent-savvy teams.hasMany relationships without breaking changes. Existing queries or eager loads (with()) remain unaffected.toSql()) simplify troubleshooting. Common pitfalls (e.g., polymorphic key mismatches) are well-documented.HasManyMerged::macro('customMerge', ...)).hasMany relationships would benefit most from merging? (Prioritize high-impact, frequently queried pairs.)collect($model->relation1)->merge($model->relation2)) that this could replace?comments over replies, or use a priority field.)commentable_guid instead of commentable_id)?UserService exposing merged activities).Post::comments + Post::replies).collect()->merge() calls) to quantify potential savings.Post or User) and replace one manual merge with hasManyMerged.// Before
$post->comments->merge($post->replies)->unique('id');
// After
$post->mergedComments; // Automatically merged and deduplicated
mergeUsing, polymorphic keys) as needed.with('mergedComments')) works as expected.0.0.2 (PHP 8.1). Check GitHub Issues for version-specific quirks.composer require korridor/laravel-has-many-merged
Post.php):
use Korridor\HasManyMerged\HasManyMerged;
class Post extends Model
{
public function mergedComments(): HasManyMerged
{
return $this->hasManyMerged(
Comment::class,
['comments', 'replies']
)->unique('id');
}
}
// Before
$comments = $post->comments->merge($post->replies);
// After
$comments = $post->mergedComments;
// Before
Post::with(['comments', 'replies'])->get();
// After
Post::with('mergedComments')->get();
How can I help you explore Laravel packages today?