{"record":{"id":"c9549388be3f8a82","repo":"cakephp/cakephp","slug":"record-not-found-in-table-s","errorCode":null,"errorMessage":"Record not found in table `%s`.","messagePattern":"Record not found in table `(.+?)`\\.","errorType":"exception","errorClass":"RecordNotFoundException","httpStatus":404,"severity":"error","filePath":"src/ORM/Query/SelectQuery.php","lineNumber":607,"sourceCode":"        if ($this->_dirty) {\n            $this->limit(1);\n        }\n\n        return $this->all()->first();\n    }\n\n    /**\n     * Get the first result from the executing query or raise an exception.\n     *\n     * @throws \\Cake\\Datasource\\Exception\\RecordNotFoundException When there is no first record.\n     * @return TSubject The first result from the ResultSet.\n     */\n    public function firstOrFail(): mixed\n    {\n        $entity = $this->first();\n        if (!$entity) {\n            $table = $this->getRepository();\n            throw new RecordNotFoundException(sprintf(\n                'Record not found in table `%s`.',\n                $table->getTable(),\n            ));\n        }\n\n        return $entity;\n    }\n\n    /**\n     * Returns an array with the custom options that were applied to this query\n     * and that were not already processed by another method in this class.\n     *\n     * ### Example:\n     *\n     * ```\n     *  $query->applyOptions(['doABarrelRoll' => true, 'fields' => ['id', 'name']);\n     *  $query->getOptions(); // Returns ['doABarrelRoll' => true]\n     * ```","sourceCodeStart":589,"sourceCodeEnd":625,"githubUrl":"https://github.com/cakephp/cakephp/blob/1128eba9b09f1946df684811350e26f2cef68fac/src/ORM/Query/SelectQuery.php#L589-L625","documentation":"SelectQuery::firstOrFail() executes the query and throws Cake\\Datasource\\Exception\\RecordNotFoundException when no row matches. The library throws it to give callers a fail-fast semantic for 'this record must exist'. The table name in the message comes from the query's repository via getTable().","triggerScenarios":"Calling ->firstOrFail() on a SELECT query whose WHERE conditions match zero rows — e.g. a wrong primary key value, a soft-delete/status filter excluding the row, or conditions built from unsanitized/unexpected input.","commonSituations":"Controller edit/view actions doing $articles->get($id) style lookups replaced by find()->where([...])->firstOrFail(); REST APIs returning 404; fixtures/seed data missing so lookups in tests fail; case-sensitivity or type mismatches (string '1' vs int 1) in the WHERE clause.","solutions":["Wrap the call in try/catch for RecordNotFoundException and handle the missing-record case (404 response, fallback)","Verify the WHERE conditions and values actually match rows (log the SQL, run it manually)","Check the row isn't excluded by a status/deleted scope on the query","If empty results are legitimate, use first() instead of firstOrFail() and null-check"],"exampleFix":"// before\n$article = $articles->find()->where(['slug' => $slug])->firstOrFail();\n// after\ntry {\n    $article = $articles->find()->where(['slug' => $slug])->firstOrFail();\n} catch (RecordNotFoundException $e) {\n    throw new NotFoundException(__(\"No article with slug {0}\", $slug));\n}","handlingStrategy":"try-catch","validationCode":"// before\n$count = $query->count(); // or: $exists = $query->count() > 0;\nif ($count === 0) { /* handle empty */ }","typeGuard":"$entity = $query->first();\nif ($entity === null) { /* not found */ }","tryCatchPattern":"use Cake\\Datasource\\Exception\\RecordNotFoundException;\ntry {\n    $entity = $query->firstOrFail();\n} catch (RecordNotFoundException $e) {\n    // return 404 / fallback entity\n}","preventionTips":["Prefer first() with a null-check when absence is a normal state","Log or include the query conditions when converting to a 404 for debuggability","Test lookups against realistic fixtures including soft-deleted rows","Cast/normalize key values (string vs int) before building WHERE conditions"],"tags":["orm","record-not-found","cakephp"],"backgroundTag":"record-not-found","analyzedSha":"1128eba9b09f1946df684811350e26f2cef68fac","analyzedAt":"2026-09-12T12:07:00.388Z","contentChangedAt":"2026-09-12T12:07:00.388Z","schemaVersion":2},"datasetVersion":"2026-09-19T12:17:13.211Z"}