Skip to content

collect() helpers accepts arguments other than iterables leading to unexpected behaviour in case of an oversight #57146

@michapietsch

Description

@michapietsch

Laravel Version

12.30.1

PHP Version

8.3.24

Database Driver & Version

No response

Description

I ran into a bug when I tried to spread two arrays into a new collection like this:

collect(
    ...[1, 2],
    ...[3, 4]
)

The result is equal to collect(1).

I simply forgot the surrounding [].

I see a chance to improve developer experience here: Communicate that the helper is being used wrong.

After all the helper is declared to accept:
@param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue>|null $value.

But it accepts e. g. 1 which is neither of these, and it silently omit the additional arguments from the array spread.

I suggest the helper could throw an invalid argument exception for non-iterable values, and/or throw when more than one argument is passed.

PHPstan requires levels 9 to catch such things.

Steps To Reproduce

In Tinker run:

collect(
    ...[1, 2]
)

The output will be:

Illuminate\Support\Collection {
    all: [
        1,
    ],
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions