Home > Mobile >  Laravel lighthouse paginate without model
Laravel lighthouse paginate without model

Time:11-25

Is there a way to use the @paginate directive from lighthouse-php without querying data from a model? Let say, i using a third party library to query data using an api or so.

CodePudding user response:

Fortunately, such a feature has been added very recently: https://github.com/nuwave/lighthouse/pull/2232. This PR added support for returning data in a Paginator from option resolver in @paginator directive.

You can provide your own function that resolves the field by directly returning data in a \Illuminate\Contracts\Pagination\Paginator instance.

This is mutually exclusive with builder and model. Not compatible with scopes and builder arguments such as @eq.

type Query {
  posts: [Post!]! @paginate(resolver: "App\\GraphQL\\Queries\\Posts")
}

A custom resolver function may look like the following:

namespace App\GraphQL\Queries;
use Illuminate\Pagination\LengthAwarePaginator;
final class Posts
{
    /**
     * @param  null  $root Always null, since this field has no parent.
     * @param  array{}  $args The field arguments passed by the client.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Shared between all fields.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Metadata for advanced query resolution.
     */
    public function __invoke($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): LengthAwarePaginator
    {
        //...apply your logic
        return new LengthAwarePaginator([
            [
                'id' => 1,
                'title' => 'Flying teacup found in solar orbit',
            ],
            [
                'id' => 2,
                'title' => 'What actually is the difference between cookies and biscuits?',
            ],
        ], 2, 15);
    }
}

(The docs are currently not getting updated correctly, which is why you probably did not find out about this. I am working on restoring the deployment.)

CodePudding user response:

Yes https://lighthouse-php.com/5/api-reference/directives.html#custom-builder :)

type Query {
  blogStatistics: [BlogStatistic!]! @paginate(builder: "App\\Blog@statistics")
}
<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

class Blog
{
    public function statistics($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): Builder
    {
        return DB::table('posts')
            ->leftJoinSub(...)
            ->groupBy(...);
    }
}
  • Related