Skip to content
This repository has been archived by the owner on Feb 10, 2019. It is now read-only.

Creating Advanced Eloquent search query and Custom filters! #370

Open
mohammad-fouladgar opened this issue Aug 20, 2018 · 0 comments
Open

Comments

@mohammad-fouladgar
Copy link
Contributor

mohammad-fouladgar commented Aug 20, 2018

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 👍

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant