laravel-lighthouse

Laravel Lighthouse pass data from parent to child


Having a nested field will call a few methods with this signature:

        $_,
        array $args,
        GraphQLContext $context,
        ResolveInfo $resolveInfo

$_ would be the parent data but you can't send anything from parent to the child, using that obviously so you have to use $resolveInfo somehow I guess.

Here's an example let's say we have a parent at properties and a child at properties.data

Here are the two functions

<?php

namespace App\GraphQL\Queries;

use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

final class PropertiesFiltered
{
    /**
     * @param null $_
     * @param array{} $args
     */
    public function parent(
        $_,
        array $args,
        GraphQLContext $context,
        ResolveInfo $resolveInfo
    ) {
        // Attempt 1   
        $resolveInfo->lookAhead()->queryPlan()["data"]["args"]["ok"] = true;
        // Attempt 2
        $resolveInfo->argumentSet->addValue("properties.data.ok", true);

        return [
            "facets" => [
                "rooms" => [
                    "step" => "1",
                ],
            ],
        ];
    }

    /**
     * @param null $_
     * @param array{} $args
     */
    public function child(
        $_,
        array $args,
        GraphQLContext $context,
        ResolveInfo $resolveInfo
    ) {
        dd($resolveInfo->argumentSet->toArray());
    }
}

None of my attempts worked in the child I always get:

array:2 [
  "first" => 0
  "page" => 10
]

which means ok doesn't get added.


Solution

  • $_, the first argument is the actual parent,

    So for the parent resolver, let's say you have:

        public function parent(
            $_,
            array $args,
            GraphQLContext $context,
            ResolveInfo $resolveInfo
        ) {
            return [
                "ok" => true,
                "facets" => [
                    "rooms" => [
                        "step" => "1",
                    ],
                ],
            ];
        }
    

    Don't worry, in the final json response, the ok property will be cleaned up by lighthouse.

    However, before that, it is passed "as-id" to the child resolvers as the parent argument. So you can get back your value in you child resolver as following:

        /**
         * @param null $_
         * @param array{} $args
         */
        public function child(
            $parent,
            array $args,
            GraphQLContext $context,
            ResolveInfo $resolveInfo
        ) {
            dd($parent['ok']); // true
        }
    

    Of course, this only works as direct parent->child relation