skip to Main Content

In resource file app/Http/Resources/PostResource.php I use method :

<?php

namespace AppHttpResources;

use IlluminateHttpResourcesJsonJsonResource;

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 AppHttpResourcesPostResource::relationLoaded()

I added PostResource class into phpstan.neon under universalObjectCratesClasses key:

includes:
    - ./vendor/nunomaduro/larastan/extension.neon

parameters:
    universalObjectCratesClasses:
        - IlluminateHttpResourcesJsonJsonResource
        - AppHttpResourcesPostResource

    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!

2

Answers


  1. This is interesting because among my codes there is a code snippet similar to yours:

    'kerzz_pos' => $this->when(
                     $this->relationLoaded('attributes') && $this->isKerzzAttributeExist(),
                     fn () => PanelBranchAttributeResource::collection($this->getKerzzAttributes())
                 ),
    

    And I use "nunomaduro/larastan": "^2.6.4". It doesn’t give me any errors either.

    Maybe you just need to upgrade the package. Or if you want to ignore it you can write a regex under the ignoreErrors setting like this:

    ignoreErrors:
         - '#Call to an undefined method (.*?)::relationLoaded().#'
    
    Login or Signup to reply.
  2. 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 AppHttpResources;
    
    use IlluminateHttpResourcesJsonJsonResource;
    
    /** @mixin Post */
    class PostResource extends JsonResource
    ....
    

    Of course adjust the model namespace for your use case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search