After upgrading to Laravel 10 I’m having hard times with Larastan errors.
The following code which was perfectly fine until 1 hour ago:
return $this->articleRepository->getDefaultArticles($organizationId)
->toBase()
->map(function (Article $article) {
return new Content(
$article->id,
$article->title,
$article->language,
);
})
->toArray();
now gives me the following error:
Parameter #1 $callback of method IlluminateSupportCollection<(int|string),IlluminateDatabaseEloquentModel>::map() expects callable(IlluminateDatabaseEloquentModel, int|string): AppAcademyContent,
Closure(AppModelsArticle): AppAcademyContent given
The repository method has the correct hint:
/**
* @return Collection<Article>
*/
public function getDefaultArticles(OrganizationId $organizationId): Collection
{
/** @var Collection<Article> */
return Article::query()
->where('organization_id', $organizationId)
->get()
->keyBy('id')
->values();
}
It gives me 115 new errors and most of them are similar to this, related to collection methods like map
and reduce
.
The quick solution would be using a temporary variable and add a type hinting:
/** @var Collection<Article> $articles */
$articles = $this->articleRepository
->getDefaultArticles($organizationId)
->toBase();
but I don’t want to do it 100 times and even the IDE is complaining that’s unnecessary
Thanks in advance for you help!
3
Answers
Instead of dealing with
PHPStan
, i found it peculiar you where callingtoBase()
here.toBase()
converts an Eloquent Collection, to a Laravel Collection.Laravel
already does something similar by default, Eloquent Collections calls it parents::map()
seen here. WhiletoArray()
has no specific implementation, thetoBase()
call is unnecessary and will avoid you the typehint trouble.If you want to fix
Larastan
. As the error states you are missing the secondmap()
parameter. Changing it to this will probably help fix the Larastan error.The only work around I found so far is to make it in 2 steps with type hinting.
it does not really help to deal with 115 new errors. But if you would have couple errors, it would help.
the solution that worked for me was downgrading phpstan: