{"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/bd6b5437e6ad87bb49f9b426724f07a9f64e9683/src/Illuminate/Database/Eloquent/Collection.php#L917-L947","documentation":"Collection::toQuery() builds a WHERE id IN (...) query against the first model's query builder. With an empty collection there is no first model, so it cannot know which table or class to query against and raises a LogicException.","triggerScenarios":"Calling $collection->toQuery() (or methods that delegate to it) when the collection has no elements, e.g. SomeModel::where(...)->get()->toQuery() after a no-row result.","commonSituations":"Chaining toQuery() directly after get() without a count check; helper code that assumes a non-empty result from a search/filter step; refactor that removed the guard clause.","solutions":["Guard with isEmpty(): if ($coll->isNotEmpty()) { $coll->toQuery(); }.","Re-query from the model class instead: SomeModel::whereKey($ids)->... when you only have IDs.","Return early or skip the branch when the upstream query produced no rows."],"exampleFix":"// before\n$query = $users->toQuery(); // $users may be empty\n\n// after\nif ($users->isNotEmpty()) {\n    $query = $users->toQuery();\n}","handlingStrategy":"validation","validationCode":"if ($collection->isEmpty()) {\n    // skip or build query from the model class instead\n    return SomeModel::query()->whereRaw('1=0');\n}\nreturn $collection->toQuery();","typeGuard":"function canBuildQuery(\\Illuminate\\Support\\Collection $c): bool\n{\n    return $c->isNotEmpty();\n}","tryCatchPattern":"try {\n    return $collection->toQuery();\n} catch (\\LogicException $e) {\n    if (str_contains($e->getMessage(), 'empty collection')) {\n        return $fallbackBuilder ?? null;\n    }\n    throw $e;\n}","preventionTips":["Always check isNotEmpty() before ->toQuery().","Prefer operating on IDs via Model::whereKey($ids) when collection provenance is uncertain.","Write a test for the empty-collection branch."],"tags":["eloquent","collection","query-builder","validation"],"analyzedSha":"bd6b5437e6ad87bb49f9b426724f07a9f64e9683","analyzedAt":"2026-08-06T00:28:32.783Z","schemaVersion":2}