folkloreinc / laravel-graphql

Facebook GraphQL for Laravel 5. It supports Relay, eloquent models, validation and GraphiQL.
1.76k stars 234 forks source link

How to paginate when using laravel-graphql? #380

Open zwl1619 opened 6 years ago

zwl1619 commented 6 years ago

How to paginate when using laravel-graphql?

spawnia commented 6 years ago

I recommend using https://github.com/nuwave/lighthouse instead. It supports pagination out of the box, without writing any code https://lighthouse-php.netlify.com/docs/next/directives.html#paginate

devlamine commented 6 years ago

with Folkloreatelier / laravel-graphql It is not possible ?

ivanfilatov commented 6 years ago

You can do like this. paginateData, prepareRelations and prepareQuery are my custom functions inside this query class (actually, i wrote abstract class for query and my custom query class looks like setting some classnames into query variables, i can share it also) The point is that in resolve() you should return an object with LengthAwarePaginator implemented.

<?php
declare(strict_types=1);

use App\GraphQL\Helpers\ResolveContext;
use Folklore\GraphQL\Support\Query;
use Folklore\GraphQL\Support\Traits\ShouldValidate;
use GraphQL;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

abstract class SomeQuery extends Query
{
    use ShouldValidate;

    public function type(): ObjectType
    {
        return GraphQL::pagination(GraphQL::type('SomeType'));
    }

    public function resolve(array $root, ?array $data, ResolveContext $context, ResolveInfo $resolveInfo): LengthAwarePaginator
    {
        $this->prepareRelations($resolveInfo);
        if ($this->prepareQuery($data)) {
            return $this->paginateData($context);
        } else {
            return new \Illuminate\Pagination\LengthAwarePaginator([], 0, $this->perPage);
        }
    }