{"id":"273c2c68bb4f21ba","repo":"laravel/framework","slug":"unable-to-create-query-for-collection-with-mixed-t","errorCode":null,"errorMessage":"Unable to create query for collection with mixed types.","messagePattern":"Unable to create query for collection with mixed types\\.","errorType":"exception","errorClass":"LogicException","httpStatus":null,"severity":"error","filePath":"src/Illuminate/Database/Eloquent/Collection.php","lineNumber":941,"sourceCode":"    /**\n     * Get the Eloquent query builder from the collection.\n     *\n     * @return \\Illuminate\\Database\\Eloquent\\Builder<TModel>\n     *\n     * @throws \\LogicException\n     */\n    public function toQuery()\n    {\n        $model = $this->first();\n\n        if (! $model) {\n            throw new LogicException('Unable to create query for empty collection.');\n        }\n\n        $class = get_class($model);\n\n        if ($this->contains(fn ($model) => ! $model instanceof $class)) {\n            throw new LogicException('Unable to create query for collection with mixed types.');\n        }\n\n        return $model->newModelQuery()->whereKey($this->modelKeys());\n    }\n}\n","sourceCodeStart":923,"sourceCodeEnd":947,"githubUrl":"https://github.com/laravel/framework/blob/bd6b5437e6ad87bb49f9b426724f07a9f64e9683/src/Illuminate/Database/Eloquent/Collection.php#L923-L947","documentation":"toQuery() needs a single concrete class to build the query. If the collection contains models of different classes (determined via instanceof of the first model's class), it raises a LogicException because no single table can satisfy the keys.","triggerScenarios":"Calling ->toQuery() on a collection holding mixed types, e.g. collect([new Post, new Comment])->toQuery(), or a polymorphic relation result that contains multiple concrete classes without a shared queryable table.","commonSituations":"Building a collection from a union of queries of different models; polymorphic 'morphMany' results that include more than one related class; manually merging model instances into one collection.","solutions":["Group by class and call toQuery() per group.","Operate on a single class only: filter the collection to one type first.","If a shared base class/table exists, re-query via that model's query builder with whereKey() on the IDs."],"exampleFix":"// before\n$models = collect([$post, $comment]);\n$models->toQuery(); // mixed types -> throws\n\n// after\n$models->groupBy(fn ($m) => get_class($m))\n    ->each(fn ($group) => $group->toQuery()->delete());","handlingStrategy":"validation","validationCode":"$types = $collection->map(fn ($m) => get_class($m))->unique();\nif ($types->count() > 1) {\n    throw new \\LogicException('Mixed types: ' . $types->implode(','));\n}\nreturn $collection->toQuery();","typeGuard":"function isHomogeneousModels(\\Illuminate\\Database\\Eloquent\\Collection $c): bool\n{\n    if ($c->isEmpty()) return false;\n    $cls = get_class($c->first());\n    return $c->every(fn ($m) => $m instanceof $cls);\n}","tryCatchPattern":"try {\n    return $collection->toQuery();\n} catch (\\LogicException $e) {\n    if (str_contains($e->getMessage(), 'mixed types')) {\n        // handle per-type\n    }\n    throw $e;\n}","preventionTips":["Group collections by class before calling toQuery().","Avoid merging different model types into one collection.","If a shared base/table exists, query from that model directly using whereKey()."],"tags":["eloquent","collection","query-builder","type-error"],"analyzedSha":"bd6b5437e6ad87bb49f9b426724f07a9f64e9683","analyzedAt":"2026-08-06T00:28:32.783Z","schemaVersion":2}