{"id":"e6570e8c8b1e3935","repo":"laravel/framework","slug":"you-must-specify-an-orderby-clause-when-using-this","errorCode":null,"errorMessage":"You must specify an orderBy clause when using this function.","messagePattern":"You must specify an orderBy clause when using this function\\.","errorType":"exception","errorClass":"RuntimeException","httpStatus":null,"severity":"error","filePath":"src/Illuminate/Database/Query/Builder.php","lineNumber":3811,"sourceCode":"            yield from $this->connection->cursor(\n                $this->toSql(), $this->getBindings(), ! $this->useWritePdo, $this->fetchUsing\n            );\n        }))->map(function ($item) {\n            return $this->applyAfterQueryCallbacks(new Collection([$item]))->first();\n        })->reject(fn ($item) => is_null($item));\n    }\n\n    /**\n     * Throw an exception if the query doesn't have an orderBy clause.\n     *\n     * @return void\n     *\n     * @throws \\RuntimeException\n     */\n    protected function enforceOrderBy()\n    {\n        if (empty($this->orders) && empty($this->unionOrders)) {\n            throw new RuntimeException('You must specify an orderBy clause when using this function.');\n        }\n    }\n\n    /**\n     * Get a collection instance containing the values of a given column.\n     *\n     * @param  \\Illuminate\\Contracts\\Database\\Query\\Expression|string  $column\n     * @param  string|null  $key\n     * @return \\Illuminate\\Support\\Collection<array-key, mixed>\n     */\n    public function pluck($column, $key = null)\n    {\n        $original = $this->columns;\n\n        // First, we will need to select the results of the query accounting for the\n        // given columns / key. Once we have the results, we will be able to take\n        // the results and get the exact data that was requested for the query.\n        $this->columns ??= is_null($key) || $key === $column","sourceCodeStart":3793,"sourceCodeEnd":3829,"githubUrl":"https://github.com/laravel/framework/blob/bd6b5437e6ad87bb49f9b426724f07a9f64e9683/src/Illuminate/Database/Query/Builder.php#L3793-L3829","documentation":"Thrown by enforceOrderBy when both $this->orders and $this->unionOrders are empty. The guard is invoked by ensureOrderForCursorPagination, so cursorPaginate/cursorPaginateUsingCursor require a deterministic row order to compute stable cursors. Without an orderBy the cursor has nothing to anchor against and pagination would return arbitrary or duplicated rows across pages.","triggerScenarios":"Calling `Model::cursorPaginate()` without any prior `->orderBy(...)`. Using cursor pagination on a view or query that has no natural ordering. Chaining `->orderByRaw('')` (which adds nothing). Switching from paginate() to cursorPaginate() on an unordered query.","commonSituations":"Adopting cursor pagination for performance on an existing endpoint that never specified order; paginating a UNION query where orders are set on a subquery not the outer builder; default scope stripping order.","solutions":["Add an orderBy before cursorPaginate: `Model::orderBy('id')->cursorPaginate()`.","Prefer ordering by a unique, monotonic column (id, created_at with id tiebreaker) for stable cursors.","For unions, order the outer query: `DB::table(...)->union(...)->orderBy('id')->cursorPaginate()`.","If order is genuinely irrelevant, use simple `paginate()`/`get()` instead of cursor pagination."],"exampleFix":"// before\nModel::cursorPaginate(20);\n// => You must specify an orderBy clause when using this function.\n\n// after\nModel::orderBy('id')->cursorPaginate(20);","handlingStrategy":"validation","validationCode":"if (empty($query->orders) && empty($query->unionOrders)) {\n    $query->orderBy($model->getKeyName());\n}\n$model::cursorPaginate();","typeGuard":"function hasOrderBy(\\Illuminate\\Database\\Query\\Builder $q): bool\n{\n    return ! empty($q->orders) || ! empty($q->unionOrders);\n}","tryCatchPattern":"try {\n    $results = $query->cursorPaginate();\n} catch (\\RuntimeException $e) {\n    if (str_contains($e->getMessage(), 'orderBy clause')) {\n        $query->orderBy($query->from.'.id');\n        $results = $query->cursorPaginate();\n    } else { throw $e; }\n}","preventionTips":["Always chain ->orderBy('id') (or another unique monotonic column) before cursorPaginate.","For unions, order the outer builder.","If order is irrelevant, switch to simple paginate() instead."],"tags":["query-builder","cursor-pagination","order-by","runtime"],"analyzedSha":"bd6b5437e6ad87bb49f9b426724f07a9f64e9683","analyzedAt":"2026-08-06T00:28:32.783Z","schemaVersion":2}