Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ahmad_aLit_town's avatar

Accessing Spatie Permissions Functions Inside GraphQl Query Always Returns NULL Values.

I'm trying to access User's Roles By Using GraphQl query ( With Rebing ) . with the getRolesNames() function from spatie library.. and always the returned date (role_id) is Null .. I Really tried hard and find nothing .. Can anyone Help me ༼ つ ◕_◕ ༽つ

0 likes
2 replies
Sinnbeck's avatar

I assume you are referring to the spatie permissions package? And showing the code that isn't working makes it easier for us to help you

1 like
ahmad_aLit_town's avatar

Sure .. This is The File I'm calling the getRolesNames() Inside UserRolesQuery.php

<?php

namespace App\GraphQl\Query\User;

use App\GraphQl\Traits\UserTrait;
use App\Models\User;

use GraphQL\Type\Definition\ResolveInfo;
use Rebing\GraphQL\Support\Facades\GraphQL;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Query;

use Closure;


class UserRolesQuery extends Query
{
    use UserTrait;

    protected $attributes = [
        'name' => 'user',
    ];

    public function type(): Type
    {
        return GraphQL::type('UserType');
    }

    public function args(): array
    {
        return [
            'id' => [
                'name' => 'id',
                'type' => Type::int(),
//                'rules' => ['required'] validation
            ],


        ];
    }

    public function resolve($root, array $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields)
    {
        $user = User::find($args['id']);
        $result =  $user->getRoleNames();
        return $result;
    }

}

And If I Printed The $result before return it ..it prints :

Illuminate\Support\Collection {#680 // app\GraphQl\Query\User\UserRolesQuery.php:46
  #items: array:1 [
    0 => "Cacher"
  ]
  #escapeWhenCastingToString: false
}

So It Seems The Roles Are Fetched Correctly !! But Why it Still Returning NULL !!

{
    "data": {
        "userRoles": {
            "role_id": null
        }
    }
}

Please or to participate in this conversation.