{"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/bd6b5437e6ad87bb49f9b426724f07a9f64e9683/src/Illuminate/Collections/Traits/EnumeratesValues.php#L380-L416","documentation":"Thrown by ensure($type) when an item in the collection does not match any of the allowed type(s). ensure() is a runtime type-check that walks every item and aborts on the first mismatch, reporting the expected type(s), the actual get_debug_type, and the position. UnexpectedValueException is thrown.","triggerScenarios":"Calling $collection->ensure(User::class) when the collection contains a null or a different model. Or ->ensure(['int', 'float']) when a string slips in. The error fires on the first offending item.","commonSituations":"Mixed data from merges/unions where a null or unexpected type sneaks in. Polymorphic relations decoded into a flat collection. Decoded JSON containing nulls where objects were expected.","solutions":["Filter out non-matching items before ensure(): $c->filter(fn($x) => $x instanceof User)->ensure(User::class).","Fix the upstream source so the collection only ever contains the expected type.","Use a broader allowed-types list if legitimate variants exist."],"exampleFix":"// before\n$collection->ensure(User::class);\n\n// after\n$collection\n    ->filter(fn ($item) => $item instanceof User)\n    ->ensure(User::class);","handlingStrategy":"type-guard","validationCode":"$filtered = $collection->filter(fn ($item) => $item instanceof $expectedType);\n$filtered->ensure($expectedType);","typeGuard":"function allOfType(\\Illuminate\\Support\\Collection $c, string $type): bool {\n    return $c->every(fn ($i) => $i instanceof $type || get_debug_type($i) === $type);\n}","tryCatchPattern":"try {\n    $collection->ensure(User::class);\n} catch (\\UnexpectedValueException $e) {\n    $collection = $collection->filter(fn ($i) => $i instanceof User);\n}","preventionTips":["Filter or validate upstream sources so collections stay homogeneous.","Add PHPStan/Psalm generics to collections to catch type drift statically.","Write a quick test asserting collection homogeneity after merges."],"tags":["laravel","collections","type-safety","runtime-check"],"analyzedSha":"bd6b5437e6ad87bb49f9b426724f07a9f64e9683","analyzedAt":"2026-08-06T00:28:32.783Z","schemaVersion":2}