PHP code example of jasco-b / query-filter

1. Go to this page and download the library: Download jasco-b/query-filter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jasco-b / query-filter example snippets


use JascoB\QueryFilter\QueryFilter;

class PostFilter extends QueryFilter
{
    protected $filterableFields = ['title'];

    public function title($query, $value)
    {
        $query->orWhere('title', 'like', '%' . $value . '%');
    }

}

use JascoB\QueryFilter\Classes\FilterColumn;

class TagFilterColumn extends FilterColumn
{
    public function apply($value)
    {
        return $this->builder->whereHas('tags', function ($query) use ($value) {
            $query->where('name', 'like', '%' . $value . '%');
        });
    }
}

use JascoB\QueryFilter\QueryFilter;

class PostFilter extends QueryFilter
{
    protected $filterableFields = ['title', 'tag'=>TagFilterColumn::class];
    
}

class PostFilter extends QueryFilter
{
    protected $filterableFields = [];

    public function __construct(Builder $builder)
    {
        parent::__construct($builder);
        $this->initFilters();
    }

    public function initFilters()
    {
        $this->filterableFields['title'] = function ($query, $value) {
            $query->where('title', 'like', "%$value%");
        };
    }
}

class Post extends Model
{
    public function scopeFilter($query, $request)
    {
        return (new PostFilter($query))->filter($request);
    }

class SearchController extends Controller
{
    public function filter(Request $request)
    {
       $posts =  Post::query()->filter($request->toArray())->get();
    }
}