🙂
I am starting a new Laravel project with Lighthouse and have been problems with resolving non root fields.
According to the documentation here for each of the fields that have complex types, there should be a model and a query provided for the field.
So in this example I have a Version
object which has two subfields: appVersion
and apiVersion
. Here is what I have in my schema.graphql
file:
type Query {
version: Version
}
type Version {
appVersion: String
apiVersion: String
}
And in addition, here is my model for Version
:
<?php
namespace AppModels;
class Version {
private string $appVersion;
private string $apiVersion;
public function __construct() {
$composer = file_get_contents('../composer.json');
$content = json_decode($composer, true);
$this->appVersion = $content['app-version'];
$this->apiVersion = $content['version'];
}
public function getAppVersion() : string {
return $this->appVersion;
}
public function getApiVersion() : string {
return $this->apiVersion;
}
function export() : array {
return [
'app' => $this->getAppVersion(),
'api' => $this->getApiVersion(),
];
}
}
And the Query file for Version
:
<?php
namespace AppGraphQLQueries;
use GraphQLTypeDefinitionResolveInfo;
use NuwaveLighthouseSupportContractsGraphQLContext;
final class Version {
public function __invoke ($version, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) {
return $version->export()[$resolveInfo->fieldName];
}
}
However the $version
seems to be always null when I try to query version using the following:
{
version {
appVersion
}
}
And I cannot figure our why. I tried to follow the docs as best as I could, but I am probably missing something really simple here :/
I should also mention that querying simple fields (like fields that don’t have a sub selection) works here for me.
Any help would be much appreciated 🙂
I implemented a graphql resolver, however the models were not resolved correctly.
2
Answers
Add @field directive to your schema:
The AppGraphQLQueriesVersion::__invoke method is a field resolver.
The first argument to that resolver is the root value. Think of it as the "parent" value from the query above that query in the tree.
In your case, you query the version from the root "Query" type, so there is no value in the tree above. That is why it is null.
Your schema definition says "There is a model with properties appVersion and apiVersion". So your Version query should return an array or class with properties appVersion and apiVersion. It does not need to be an eloquent model.