larastan: [API Resources] Call to an undefined method

  • Larastan Version: v0.3.4
  • --level used: 5

Description:

Laravel has Eloquent Resources to make it easy to standardize model output for API usage.

In my case I’ve got the Spatie Permissions package installed to handle roles and permissions. That package adds a getAllPermissions() method to the User model. And this works great. However, Larastan does not detect this and flags it as an undefined method.

Laravel code where the issue was found:


namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

/**
 * Defines a user resource.
 */
class UserResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     *
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function toArray($request)
    {
        return [
            'name'        => $this->name,
            'email'       => $this->email,
            'permissions' => $this->getAllPermissions()->pluck('name')->toArray(),
        ];
    }
}

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 21 (9 by maintainers)

Most upvoted comments

You can add @mixin <ModelClass> to the docblock of your resource class.

@canvural not working in my case 😦

image

@SagarNaliyapara @johanvanhelden JsonResource is not generic anymore. I already wrote the solution to this problem 4 years ago: https://github.com/nunomaduro/larastan/issues/176#issuecomment-542889501

Just found a better solution from Upgrade guide - https://github.com/nunomaduro/larastan/blob/master/UPGRADE.md#eloquent-resources

May help someone

Yeah, this is the solution I have been using.

Just found a better solution from Upgrade guide - https://github.com/nunomaduro/larastan/blob/master/UPGRADE.md#eloquent-resources

May help someone

I was just looking at the issue and shared that link.