#2308·larastan

Allow merging different types into base Collection

Author: mortenscheelCreated Jun 27, 2025Updated Aug 31, 2026
Labelsenhancement

Feature Request

Additional context Example:

php
$apples = collect([new Apple, new Apple]);
$oranges = collect([new Orange, new Orange]);
$merged = $apples->merge($oranges);

Result:

Parameter #1 $items of method Illuminate\Support\Collection<int,App\Apple>::merge() expects
 Illuminate\Contracts\Support\Arrayable<int, App\Apple>|iterable<int, App\Apple>,
 Illuminate\Support\Collection<int, App\Orange> given.
 argument.type

This error make perfect sense for Eloquent collection where all items must be the same type of model.

But base collections don't have that limitation, so it would be nice if Larastan could make PHPStan be a bit more flexible with those.

I realize that those errors are raised because the docblock on Illuminate\Support\Collection::merge() asserts that the "incoming" items are of the same type as the collection instance. But maybe Larastan can override this to return the union type as TValue?

I've tried changing the docblock to this, and it seemed to do the trick, but I don't know if it's the right way to do it

php
/**
 * Merge the collection with the given items.
 * @template UKey of array-key
 * @template UValue
 *
 * @param  \Illuminate\Contracts\Support\Arrayable<UKey, UValue>|iterable<UKey, UValue>  $items
 * @return static<TKey|UKey, TValue|UValue>
 */

Would you be interested in a PR with this sort of "unionizing" in all the relevant methods of the base collection?