mongodb/laravel-mongodb · error · LogicException

is not supported for relation aggregates.

Error message

%s is not supported for relation aggregates.

What it means

Only certain relation types support aggregates in MongoDB Laravel: EmbedsOneOrMany, HasOneOrMany, BelongsToMany, and BelongsTo (except MorphTo). Any other relation class (e.g. MorphTo, MorphToMany variants not covered, or custom relation classes) throws this LogicException naming the relation class via class_basename.

Solutions

  1. Remove withAggregate/withCount on the morphTo/custom relation.
  2. Aggregate per morph type instead: filter by morph type and use withCount on the concrete hasMany relations per type.
  3. Compute the count manually in PHP after fetching parents, grouping by morph type and id.

Example fix

// before
Like::withCount('likeable')->get(); // morphTo not supported
// after
$likes = Like::with('likeable')->get();
$counts = $likes->groupBy(fn ($l) => $l->likeable::class)->map->count();
Defensive patterns

Strategy: validation

Validate before calling

// Check relation type before using withAggregate
$relation = (new Model())->morphToRelation();
if (!$relation instanceof \MongoDB\Laravel\Relations\EmbedsOneOrMany
    && !$relation instanceof \Illuminate\Database\Eloquent\Relations\HasOneOrMany
    && !$relation instanceof \Illuminate\Database\Eloquent\Relations\BelongsToMany
    && (!$relation instanceof \Illuminate\Database\Eloquent\Relations\BelongsTo || $relation instanceof \Illuminate\Database\Eloquent\Relations\MorphTo)) {
    throw new LogicException('Relation type not supported for aggregates.');
}

Type guard

function supportsRelationAggregate(object $relation): bool {
    return $relation instanceof \MongoDB\Laravel\Relations\EmbedsOneOrMany
        || $relation instanceof \Illuminate\Database\Eloquent\Relations\HasOneOrMany
        || $relation instanceof \Illuminate\Database\Eloquent\Relations\BelongsToMany
        || ($relation instanceof \Illuminate\Database\Eloquent\Relations\BelongsTo && !$relation instanceof \Illuminate\Database\Eloquent\Relations\MorphTo);
}

Try / catch

try {
    $result = Model::withCount('morphToRelation')->get();
} catch (\LogicException $e) {
    // compute counts manually grouped by morph type
    $result = Model::with('morphToRelation')->get();
}

Prevention

When it happens

Trigger: Calling withCount/withSum etc. with a morphTo relation ( polymorphic inverse), e.g. Model::withCount('morphToRelation'), or any custom Relation subclass not in the supported list.

Common situations: Polymorphic inverse relations: a commentable morphTo relation cannot be aggregated because the target table/type varies per row; custom relation classes written by the app are also unsupported.

Understand the failure class

Background: UnsupportedOperationException and "is not supported" errors: when a library deliberately refuses a call — this error's family across 30 libraries.

Related errors


AI-assisted analysis of mongodb/laravel-mongodb@0634653039 (2026-09-15). Data as JSON: /api/errors/ebed721582d28a53. Report an issue: GitHub.

Appendix: source

Thrown at src/Helpers/QueriesRelationshipAggregates.php:310

            return;
        }

        if (! DocumentModel::isDocumentModel($relation->getRelated()) || $this->isAcrossConnections($relation)) {
            throw new LogicException(sprintf(
                'Aggregating the hybrid relation "%s" is not supported. The related model must be stored in MongoDB.',
                $name,
            ));
        }

        if (
            $relation instanceof HasOneOrMany
            || $relation instanceof BelongsToMany
            || ($relation instanceof BelongsTo && ! $relation instanceof MorphTo)
        ) {
            return;
        }

        throw new LogicException(sprintf(
            '%s is not supported for relation aggregates.',
            class_basename($relation),
        ));
    }

    private function getAggregateParentKey(Relation $relation): ?string
    {
        return match (true) {
            $relation instanceof HasOneOrMany => $relation->getLocalKeyName(),
            $relation instanceof BelongsTo => $relation->getForeignKeyName(),
            $relation instanceof BelongsToMany => $relation->getParentKeyName(),
            default => null,
        };
    }

    /** The aggregated value does not exist in the documents, the server cannot use it. */
    private function assertAggregateNotUsedInQuery(string $alias): void
    {

View on GitHub (pinned to 0634653039)