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.
Strengths:
hasMany. The HasManyMerged relationship extends Eloquent’s query builder, enabling seamless integration with eager loading (with()), constraints (whereHas), and serialization (e.g., JsonResource).UNION, JOIN, or subqueries), reducing N+1 queries and post-processing overhead. Supports pagination and constraints (e.g., whereHas) out of the box.comments and replies across polymorphic models) with configurable merge logic via mergeUsing. Accommodates edge cases like deduplication or field prioritization.hasMany.Limitations:
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.whereHas) is critical for performance at scale.*_id/*_type). Custom key mappings (e.g., commentable_uuid) may require overrides or additional configuration.hasMany relationships without breaking changes. Existing queries, eager loads (with()), and serializers remain unaffected.toSql(), Debugbar) to inspect generated queries. Useful for optimizing performance or troubleshooting.orders and returns) and API references. Release notes highlight breaking changes and new features.belongsToMany), implement custom macros or traits extending HasManyMerged. Example:
use Korridor\HasManyMerged\HasManyMerged;
class BelongsToManyMerged extends HasManyMerged
{
// Custom logic for belongsToMany support
}
hasMany relationships are most frequently merged manually? Prioritize high-impact, repetitive patterns (e.g., User::orders()->merge($user->returns)).commentable_uuid)? If so, assess the effort to override default key handling.created_at, use a priority field, or deduplicate by id.) The mergeUsing callback can handle this.comments only for published posts.) Evaluate whether whereHas or custom constraints suffice.// 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
UserService exposing merged activities to a frontend.// Merge media and attachments
class Post extends Model
{
public function mediaMerged()
{
return $this->hasManyMerged([
'media' => Media::class,
'attachments' => Attachment::class,
]);
}
}
collect()->merge(), array_merge()). Use static analysis tools (e.g., PHPStan) to detect ad-hoc merging.User::transactions merging orders, returns, andHow can I help you explore Laravel packages today?