folkloreinc / laravel-graphql

Facebook GraphQL for Laravel 5. It supports Relay, eloquent models, validation and GraphiQL.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Creating Advanced Eloquent search query and Custom filters!

mohammad-fouladgar opened this issue · comments

Usable to : #292 #317
Hi guys,

I recently needed to implement a search feature in the project that included many filters.

I decided to build a flexible and scalable search system and put it in the GitHub repository.

Quick Usage

Suppose you want to get the products list by filter categories:

<?php

namespace App\GraphQL\Query;

use App\Entities\Product;
use Folklore\GraphQL\Support\Query;
use Fouladgar\EloquentBuilder\EloquentBuilder;
use GraphQL;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;

class ProductSearch extends Query
{
    protected $attributes = [
        'name'        => 'ProductSearch',
        'description' => 'A query for advanced search products',
    ];

    public function type()
    {
        return GraphQL::type('ProductSearched');
    }

       public function args()
    {
        return [
            'categories' => [
                'name' => 'categories',
                'type' => Type::listOf(Type::id()),
            ],
        ];
    }

    public function resolve($root, $args, $context, ResolveInfo $info)
    {
        $products = EloquentBuilder::to(Product::class, $args);

        return $products->get();
    }
}

Defining Filters

You need to define a filter for each parameter that you want to add to the query.
For Example:

<?php

namespace App\EloquentFilters\Product;

use Fouladgar\EloquentBuilder\Support\Foundation\Contracts\Filter;
use Illuminate\Database\Eloquent\Builder;

class CategoriesFilter implements Filter
{
    /**
     * Apply the filter to a given Eloquent query builder.
     *
     * @param Builder $builder
     * @param mixed   $values
     *
     * @return Builder
     */
    public function apply(Builder $builder, $values): Builder
    {
        return $builder->where(function ($query) use ($values) {
            $query->whereHas('categories', function ($query) use ($values) {
                $query->whereIn('category_id', $values);
            });
        });
    }
}

See the GitHub repository for more details.
Thank you 👍