{"record":{"id":"5df98d4c7e01e9a4","repo":"laravel/framework","slug":"unable-to-create-query-for-empty-collection","errorCode":null,"errorMessage":"Unable to create query for empty collection.","messagePattern":"Unable to create query for empty collection\\.","errorType":"exception","errorClass":"LogicException","httpStatus":null,"severity":"error","filePath":"src/Illuminate/Database/Eloquent/Collection.php","lineNumber":935,"sourceCode":"            }\n        });\n\n        return $connection;\n    }\n\n    /**\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":917,"sourceCodeEnd":947,"githubUrl":"https://github.com/laravel/framework/blob/e0f6eb3518ac29fbbca8529e97d0df7fc9f24481/src/Illuminate/Database/Eloquent/Collection.php#L917-L947","documentation":"Thrown by Eloquent\\Collection::toQuery() when the collection is empty. toQuery() builds an Eloquent query builder scoped to the models in the collection via whereKey($this->modelKeys()); with no first() element there is no model to derive a newModelQuery() from, so Laravel refuses rather than guess a class.","triggerScenarios":"Calling $collection->toQuery() on a collection that returned zero results from a query (e.g. User::where('active', false)->get()->toQuery()), or calling toQuery() on a freshly new-upped collection with no items.","commonSituations":"Chaining toQuery() after a filter that may yield zero rows; calling toQuery() inside a loop where some iterations produce empty collections; refactoring a loop that assumed at least one result.","solutions":["Guard the call: if ($collection->isNotEmpty()) { $collection->toQuery(); }.","Build the query up-front from the builder instead of round-tripping through a collection (e.g. keep the Builder and add whereKey()).","If you need a query for an empty set, instantiate the model query explicitly: User::query()->whereKey([])."],"exampleFix":"// before\n$collection = User::where('active', false)->get();\n$collection->toQuery(); // LogicException when empty\n\n// after\nif ($collection->isNotEmpty()) {\n    $collection->toQuery()->update(['flagged' => true]);\n}","handlingStrategy":"validation","validationCode":"if ($collection->isEmpty()) {\n    // nothing to query; handle gracefully\n    return;\n}\n$query = $collection->toQuery();","typeGuard":"function isNonEmpty(\\Illuminate\\Support\\Collection $c): bool\n{\n    return $c->isNotEmpty();\n}","tryCatchPattern":null,"preventionTips":["Always guard toQuery() with isNotEmpty().","Prefer operating on a Builder (kept from the query) rather than round-tripping through a collection.","Write tests that exercise the empty-collection path for any code calling toQuery()."],"tags":["eloquent","collection","query-builder","empty-state"],"backgroundTag":null,"analyzedSha":"e0f6eb3518ac29fbbca8529e97d0df7fc9f24481","analyzedAt":"2026-08-11T20:52:37.562Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}