Laravel-permission: How to use as an include in a fractal transformer?

Created on 10 May 2017  路  3Comments  路  Source: spatie/laravel-permission

I am using repositories to create and manage roles and permissions for a user.

I have a function that allows me to include certain pieces of data in a request, however when I do it like this:

/**
 * Class UserTransformer
 * @package namespace App\Transformers;
 */
class UserTransformer extends TransformerAbstract
{
    protected $availableIncludes = ['roles', 'permissions'];

    /**
     * Transform the \User entity
     * @param User $model
     *
     * @return array
     */
    public function transform(User $model)
    {
        $data = array_only($model->toArray(), $model->getFillable());
        return [
            'id'         => (int) $model->id,
            'type' => $model->getModelName(),
            'attributes' => $data
        ];
    }

    public function includeRoles(User $model)
    {
        return $this->collection($model->roles, new RoleTransformer());
    }

    public function includePermissions(User $model)
    {
        return $this->collection($model->permissions, new PermissionTransformer());
    }
}

I get an error saying:

Argument 1 passed to App\\Transformers\\RoleTransformer::transform() must be an instance of App\\Models\\Role, instance of Spatie\\Permission\\Models\\Role given

I know it isnt technically an issue on the package, and more on my side, but I am looking for assistance on how to have these included

Most helpful comment

Face Palms

All 3 comments

Could it be that you have a wrong use statement in your RoleTransformer?

Should be use Spatie\Permission\Models\Role, your error shows that you currently have use App\Models\Role.

Looks like you're importing the wrong namespace in your RoleTransformer. In the class replace

use App\Models\Role;

by

use Spatie\Permission\Models\Role;

Face Palms

Was this page helpful?
0 / 5 - 0 ratings

Related issues

feliperoan picture feliperoan  路  3Comments

MichalKrakow picture MichalKrakow  路  4Comments

tripex picture tripex  路  3Comments

antweny picture antweny  路  4Comments

ionesculiviucristian picture ionesculiviucristian  路  4Comments