I'm creating a Laravel backend for a Nuxt app, and am using Lighthouse-PHP to deliver data via GraphQL.
I'm trying to set up a query to do a find by slug instead of the default ID. When I run the query in the graphql playground, it correctly returns the data, however when I load the page on the frontend, it returns null
.
Backend
schema.graphql
type Query {
forumCategoryBySlug(slug: String! @eq): ForumCategory @find
}
type ForumCategory {
id: ID!
title: String!
description: String!
slug: String!
subcategories: [ForumSubcategory!]! @hasMany
created_at: DateTime!
updated_at: DateTime!
}
ForumCategory.php model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class ForumCategory extends Model
{
protected $fillable = [
'title', 'description', 'slug'
];
public function subcategories(): HasMany
{
return $this->hasMany(ForumSubcategory::class);
}
}
Frontend
Index.vue
import categoryQuery from '~/apollo/queries/forum/category.gql';
export default {
apollo: {
category: {
prefetch: false,
fetchPolicy: 'network-only',
query: categoryQuery,
variables () {
return {
slug: this.$route.params.slug
};
}
}
},
}
category.gql
query Category($slug: String!) {
category: forumCategoryBySlug(slug: $slug) {
id
title
description
slug
}
}
I feel like I've triple-checked every little thing but can't for the life of me figure out why the data is still returning null
. Any help would be greatly appreciated!
Figured it out after a few days. Essentially I needed to create a custom resolver.
schema.graphql
type Query {
forumCategoryBySlug(slug: String! @eq): ForumCategory
}
app/GraphQL/Queries/ForumCategoryBySlug.php
<?php
namespace App\GraphQL\Queries;
use App\Models\ForumCategory;
class ForumCategoryBySlug
{
/**
* @param null $_
* @param array<string, mixed> $args
*/
public function __invoke($_, array $args)
{
$category = \App\Models\ForumCategory::findBySlug($args["slug"])->first();
return $category;
}
}