Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

collection keyBy / groupBy #19

Closed
makroxyz opened this issue Sep 25, 2024 · 2 comments
Closed

collection keyBy / groupBy #19

makroxyz opened this issue Sep 25, 2024 · 2 comments
Labels
bug Something isn't working

Comments

@makroxyz
Copy link

makroxyz commented Sep 25, 2024

  • Larastan Version: 2.10.10
  • Laravel Version: 11.24.1

Description

Unable to resolve the template type TNewKey in call to method Illuminate\Support\Collection<int,App\Models\MyModel>::keyBy()

Laravel code where the issue was found

$a = MyModel::all()->keyBy('id');

Sorry... but I can't understand how to solve this...

@makroxyz makroxyz added the bug Something isn't working label Sep 25, 2024
@calebdw
Copy link
Owner

calebdw commented Sep 25, 2024

Hello!

The framework added better generics in laravel/framework#52787, so now PHPStan can determine what the collection key type should be. However, this only works for closures:

$a = MyModel::all()->keyBy('id');              // Collection<(int|string), MyModel>
$a = MyModel::all()->keyBy(fn ($m) => $m->id); // Collection<int, MyModel>

If you want to just use a string, then you can ignore the error locally (or globally):

/** @phpstan-ignore argument.templateType */
$a = MyModel::all()->keyBy('id');

This is the best we can do with just PHPDocs, but I'm thinking about writing an extension in Larastan that will be able to determine the type even if an array/string is passed

@calebdw calebdw closed this as completed Sep 25, 2024
@makroxyz
Copy link
Author

makroxyz commented Sep 25, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants