skip to Main Content

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

enter image description here

Thanks in advance for you help!

3

Answers


  1. Instead of dealing with PHPStan, i found it peculiar you where calling toBase() 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. While toArray() has no specific implementation, the toBase() call is unnecessary and will avoid you the typehint trouble.

    If you want to fix Larastan. As the error states you are missing the second map() parameter. Changing it to this will probably help fix the Larastan error.

    ->map(function (Article $article, int $key) {
    
    Login or Signup to reply.
  2. The only work around I found so far is to make it in 2 steps with type hinting.

    /** @var IlluminateSupportCollection $result */
    $result = $this->articleRepository->getDefaultArticles($organizationId);
    
    return $result->map(function (Article $article) {
        return new Content(
            $article->id,
            $article->title,
            $article->language,
        );
    })
    ->toArray();
    

    it does not really help to deal with 115 new errors. But if you would have couple errors, it would help.

    Login or Signup to reply.
  3. the solution that worked for me was downgrading phpstan:

    $ composer require phpstan/phpstan:1.10.11 --dev
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search