In resource file app/Http/Resources/PostResource.php I use method :
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class PostResource extends JsonResource
{
public function toArray($request)
{
$data = [
'id' => $this->id,
...
'mediaProp'=> $this->when($this->relationLoaded('mediaProp'), new MediaPropResource($this->mediaProp)),
];
But I got error when running larastan command :
Call to an undefined method App\Http\Resources\PostResource::relationLoaded()
I added PostResource class into phpstan.neon under universalObjectCratesClasses key:
includes:
- ./vendor/nunomaduro/larastan/extension.neon
parameters:
universalObjectCratesClasses:
- Illuminate\Http\Resources\Json\JsonResource
- App\Http\Resources\PostResource
paths:
- app/
# Level 9 is the highest level
level: 5
# ignoreErrors:
# - '#PHPDoc tag @var#'
#
# excludePaths:
# - ./*/*/FileToBeExcluded.php
#
# checkMissingIterableValueType: false
But that does not help and i still got the same error. How can I fix it ?
"laravel/framework": "^10.8",
"nunomaduro/larastan": "^2.0",
Thanks in advance!
relationLoaded
is a method that is defined in HasRelationships
trait of Laravel. But PHPStan does not know the relation between a resource and model. So you need to add a @mixin
annotation to your resource class. Like so:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin Post */
class PostResource extends JsonResource
....
Of course adjust the model namespace for your use case.