{"record":{"id":"fe3d63f527963038","repo":"laravel/framework","slug":"collection-should-only-include-s-items-but-s","errorCode":null,"errorMessage":"Collection should only include [%s] items, but '%s' found at position %d.","messagePattern":"Collection should only include \\[(.+?)\\] items, but '(.+?)' found at position (.+?)\\.","errorType":"exception","errorClass":"UnexpectedValueException","httpStatus":null,"severity":"error","filePath":"src/Illuminate/Collections/Traits/EnumeratesValues.php","lineNumber":398,"sourceCode":"     * @param  class-string<TEnsureOfType>|array<array-key, class-string<TEnsureOfType>>|'string'|'int'|'float'|'bool'|'array'|'null'  $type\n     * @return static<TKey, TEnsureOfType>\n     *\n     * @throws \\UnexpectedValueException\n     */\n    public function ensure($type)\n    {\n        $allowedTypes = is_array($type) ? $type : [$type];\n\n        return $this->each(function ($item, $index) use ($allowedTypes) {\n            $itemType = get_debug_type($item);\n\n            foreach ($allowedTypes as $allowedType) {\n                if ($itemType === $allowedType || $item instanceof $allowedType) {\n                    return true;\n                }\n            }\n\n            throw new UnexpectedValueException(\n                sprintf(\"Collection should only include [%s] items, but '%s' found at position %d.\", implode(', ', $allowedTypes), $itemType, $index)\n            );\n        });\n    }\n\n    /**\n     * Determine if the collection is not empty.\n     *\n     * @phpstan-assert-if-true TValue $this->first()\n     * @phpstan-assert-if-true TValue $this->last()\n     *\n     * @phpstan-assert-if-false null $this->first()\n     * @phpstan-assert-if-false null $this->last()\n     *\n     * @return bool\n     */\n    public function isNotEmpty()\n    {","sourceCodeStart":380,"sourceCodeEnd":416,"githubUrl":"https://github.com/laravel/framework/blob/e0f6eb3518ac29fbbca8529e97d0df7fc9f24481/src/Illuminate/Collections/Traits/EnumeratesValues.php#L380-L416","documentation":"Thrown by Collection::ensure($type) when an item in the collection does not match any of the allowed types. The method iterates every item, compares get_debug_type($item) against the allowed list (and an instanceof check), and throws UnexpectedValueException at the first mismatch with the position and actual type. It is the runtime type-enforcement analogue of PHPDoc generics.","triggerScenarios":"->ensure(User::class) when the collection contains a non-User object or a scalar; ->ensure(['int','string']) when a null/float is present; mixing data from a query that returned unexpected rows.","commonSituations":"Collection built from an external/unguarded source (CSV, API payload, DB raw query) that includes nulls or unexpected types; refactoring a heterogeneous collection to typed after the fact.","solutions":["Filter/map the collection to the expected type before calling ensure.","Pass an array of allowed types to accept a union: ->ensure(['int','string']).","Fix the upstream producer so only valid items enter the collection."],"exampleFix":"// before\n$collection->ensure(User::class);\n// after\n$users = $collection->filter(fn ($i) => $i instanceof User);\n$users->ensure(User::class);","handlingStrategy":"type-guard","validationCode":"$allowed = [\\App\\Models\\User::class];\n$bad = $collection->first(fn ($i) => ! (is_object($i) && ($i instanceof \\App\\Models\\User)));\nif ($bad !== null) {\n    throw new \\UnexpectedValueException('Collection contains non-User item.');\n}\n$collection->ensure(\\App\\Models\\User::class);","typeGuard":"function isUserCollection(\\Illuminate\\Support\\Collection $c): bool {\n    return $c->every(fn ($i) => $i instanceof \\App\\Models\\User);\n}","tryCatchPattern":"try {\n    $collection->ensure(\\App\\Models\\User::class);\n} catch (\\UnexpectedValueException $e) {\n    // log and filter out offending items\n    $collection = $collection->filter(fn ($i) => $i instanceof \\App\\Models\\User);\n}","preventionTips":["Type-check items at the producer boundary (DB, API, CSV import).","Use every() to validate before ensure() in defensive code paths.","Prefer Eloquent collections which are already typed over generic ones."],"tags":["collections","type-safety","validation","laravel"],"backgroundTag":null,"analyzedSha":"e0f6eb3518ac29fbbca8529e97d0df7fc9f24481","analyzedAt":"2026-08-11T20:52:37.562Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}