laravel/framework · error · LogicException

Unable to create query for collection with mixed types.

Error message

Unable to create query for collection with mixed types.

What it means

Thrown by Eloquent\Collection::toQuery() when the collection contains models of more than one concrete class. toQuery() derives the query from the first model's class and then uses whereKey(); it checks every element via contains(fn ($model) => ! $model instanceof $class) and rejects mixed types because a single query cannot target two tables.

Solutions

  1. Split the collection by class with groupBy(fn ($m) => get_class($m)) and call toQuery() per group.
  2. Rebuild the data so only one model type is present before calling toQuery().
  3. Use separate per-type query/update calls instead of one combined query.

Example fix

// before
$collection = $users->concat($posts);
$collection->toQuery()->delete(); // LogicException

// after
$collection->groupBy(fn ($m) => get_class($m))
    ->each(fn ($group) => $group->toQuery()->delete());
Defensive patterns

Strategy: validation

Validate before calling

$classes = $collection->map(fn ($m) => get_class($m))->unique();
if ($classes->count() > 1) {
    throw new \LogicException('Collection mixes model types: ' . $classes->implode(', '));
}
$query = $collection->toQuery();

Type guard

function isHomogeneousByClass(\Illuminate\Support\Collection $c): bool
{
    return $c->map(fn ($m) => get_class($m))->unique()->count() === 1;
}

Prevention

When it happens

Trigger: Calling toQuery() on a collection built from merge()/concat() of different model types, or on a polymorphic relation collection that holds more than one concrete model class. The contains() check fires on the second distinct class.

Common situations: Combining results from two models and then trying to update them together; a custom relation that returns mixed concrete types; storing base-class instances and subclass instances together.

Related errors


AI-assisted analysis of laravel/framework@e0f6eb3518 (2026-08-11). Data as JSON: /api/errors/273c2c68bb4f21ba. Report an issue: GitHub.

Appendix: source

Thrown at src/Illuminate/Database/Eloquent/Collection.php:941

    /**
     * Get the Eloquent query builder from the collection.
     *
     * @return \Illuminate\Database\Eloquent\Builder<TModel>
     *
     * @throws \LogicException
     */
    public function toQuery()
    {
        $model = $this->first();

        if (! $model) {
            throw new LogicException('Unable to create query for empty collection.');
        }

        $class = get_class($model);

        if ($this->contains(fn ($model) => ! $model instanceof $class)) {
            throw new LogicException('Unable to create query for collection with mixed types.');
        }

        return $model->newModelQuery()->whereKey($this->modelKeys());
    }
}

View on GitHub (pinned to e0f6eb3518)