Skip to content

Wrong/Too strict type annotation for Collection::unique #40897

Closed
@NiclasvanEyk

Description

@NiclasvanEyk
  • Laravel Version: 9.0.0
  • PHP Version: 8.1.1
  • Database Driver & Version: /

Description:

Currently the $key parameter of the Collection::unique method has the following type annotation:

    /**
     * Return only unique items from the collection array.
     *
     * @param  (callable(TValue, TKey): bool)|string|null  $key
     * @param  bool  $strict
     * @return static
     */
    public function unique($key = null, $strict = false)

So basically it can be

  • a function that returns bool
  • a string
  • nothing at all

I think the first one is a little bit too strict. Looking at https://laravel.com/docs/9.x/collections#method-unique I should be able to return any value to determine uniqueness:

Finally, you may also pass your own closure to the unique method to specify which value should determine an item's uniqueness:

$unique = $collection->unique(function ($item) {
    return $item['brand'].$item['type'];
});
 
$unique->values()->all();
 
/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
        ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    ]
*/

Suggestions

Not sure what makes the most sense here, I guess it would make sense for the function to return mixed instead of bool, but I am sure @nunomaduro knows more, since he made the adjustments in #39323?

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