laravel/framework · error · UnexpectedValueException

Collection should only include [%s] items, but '%s' found at

Error message

Collection should only include [%s] items, but '%s' found at position %d.

What it means

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.

Source

Thrown at src/Illuminate/Collections/Traits/EnumeratesValues.php:398

     * @param  class-string<TEnsureOfType>|array<array-key, class-string<TEnsureOfType>>|'string'|'int'|'float'|'bool'|'array'|'null'  $type
     * @return static<TKey, TEnsureOfType>
     *
     * @throws \UnexpectedValueException
     */
    public function ensure($type)
    {
        $allowedTypes = is_array($type) ? $type : [$type];

        return $this->each(function ($item, $index) use ($allowedTypes) {
            $itemType = get_debug_type($item);

            foreach ($allowedTypes as $allowedType) {
                if ($itemType === $allowedType || $item instanceof $allowedType) {
                    return true;
                }
            }

            throw new UnexpectedValueException(
                sprintf("Collection should only include [%s] items, but '%s' found at position %d.", implode(', ', $allowedTypes), $itemType, $index)
            );
        });
    }

    /**
     * Determine if the collection is not empty.
     *
     * @phpstan-assert-if-true TValue $this->first()
     * @phpstan-assert-if-true TValue $this->last()
     *
     * @phpstan-assert-if-false null $this->first()
     * @phpstan-assert-if-false null $this->last()
     *
     * @return bool
     */
    public function isNotEmpty()
    {

View on GitHub (pinned to bd6b5437e6)

Solutions

  1. Filter out non-matching items before ensure(): $c->filter(fn($x) => $x instanceof User)->ensure(User::class).
  2. Fix the upstream source so the collection only ever contains the expected type.
  3. Use a broader allowed-types list if legitimate variants exist.

Example fix

// before
$collection->ensure(User::class);

// after
$collection
    ->filter(fn ($item) => $item instanceof User)
    ->ensure(User::class);
Defensive patterns

Strategy: type-guard

Validate before calling

$filtered = $collection->filter(fn ($item) => $item instanceof $expectedType);
$filtered->ensure($expectedType);

Type guard

function allOfType(\Illuminate\Support\Collection $c, string $type): bool {
    return $c->every(fn ($i) => $i instanceof $type || get_debug_type($i) === $type);
}

Try / catch

try {
    $collection->ensure(User::class);
} catch (\UnexpectedValueException $e) {
    $collection = $collection->filter(fn ($i) => $i instanceof User);
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of laravel/framework@bd6b5437e6 (2026-08-06). Data as JSON: /data/errors/fe3d63f527963038.json. Report an issue: GitHub.