カテゴリー
Linux

Laravel 8 、 Larastan 1.0.3 。API リソースクラスに対してプロパティが無いエラー、例えば Access to an undefined property App\Http\Resources\UserResource::$id. に対応する方法メモ

対応方法まとめ

  • その1
    • API リソースクラスの toArray メソッド冒頭に、例えば /** @var \App\Models\User $this */ と書く。
    • 要は、 PHPDocs で API リソースクラスで使用するモデルを $this に紐づければ良いようだ。
  • その2
    • クラスコメントに、例えば /** @mixin \App\Models\User */ と書く。
    • 要は、 PHPDocs で API リソースクラスに使用するモデルを混ぜ込めば良いようだ。

エラーメッセージの全容

app@b08dd89b31aa:/var/www/html/laravel$ vendor/bin/phpstan --memory-limit=-1
Note: Using configuration file /var/www/html/laravel/phpstan.neon.dist.

... 略 ...

 ------ -------------------------------------------------------------------------- 
  Line   Http/Resources/UserResource.php                                           
 ------ -------------------------------------------------------------------------- 
  18     Access to an undefined property App\Http\Resources\UserResource::$id.     
  19     Access to an undefined property App\Http\Resources\UserResource::$name.   
  20     Access to an undefined property App\Http\Resources\UserResource::$email.  
 ------ -------------------------------------------------------------------------- 

... 略 ...

app@b08dd89b31aa:/var/www/html/laravel$

対応方法 1. PHPDocs で API リソースクラスで使用するモデルを $this に紐づける、のコード

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request): array
    {
        /** @var \App\Models\User $this */
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }
}

対応方法 2. PHPDocs で API リソースクラスに使用するモデルを混ぜ込む、のコード

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

/** @mixin \App\Models\User */
class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }
}

おわりに

検索しても見つからなかったのでメモ、、、と思いまして今再度検索してみましたら、、、解決方法でてきました。。。それも、自分のコードよりも、よりふさわしそうです。。。

というわけで、対応方法その2を追記しております。

さらに、 PHPDocs の @mixin をなんとなく調べましたら、まさに今回の 2 つ目の方法について、便利だよと紹介するページにもヒットいたしました。

解決してからブログ記事を執筆し、その時に検索すると解決方法ズバリがヒットする現象あるある、今回もいただきました。。。

以上です。

コメントを残す